[Django]-Django REST Framework serializer โ€“ access existing foreign key

3๐Ÿ‘

โœ…

It will be like

try:
    category = Category.objects.get(format=format, page=page, order=order)
except Category.DoesNotExist:
    # either make it None or create new category, depends on your requirement
    category = None
    # or create new category
except Category.MultipleObjectsReturned:
    category = category.first() # it depends on your requirement
item.category = category
๐Ÿ‘คUmar Asghar

2๐Ÿ‘

At least there is one error,you should use get to get only one category as you itemโ€™s category instead of use filter to get queryset.

class ItemSerializer(serializers.ModelSerializer):
    category = CategorySerializer()
    data = serializers.ListField()

    class Meta:
        model = Item
        fields = ('username', 'title', 'category', 'data')

    def create(self, validated_data):
        category_dict = validated_data.pop('category')
        item = Item.objects.create(**validated_data)
        format = category_dict.format
        page = category_dict.page
        order = category_dict.order
        try:
            item.category = Category.objects.get(format=format, page=page, order=order)
        except  Category.DoesNotExist:
            pass
        except  Category.MultipleObjectsReturned:
            pass
        return item
๐Ÿ‘คYkh

Leave a comment