ottomd
ottomd

Reputation: 437

How to use custom variables in serializers?

I want to create a serializer that uses the variables from my model and also counts how many data of the same id is found in the table.

I have created this, but it doesn't work:

class WebsiteSerializer(serializers.Serializer):
    item_nr = serializers.IntegerField()

    class Meta:
        model = URL
        fields = (
            "id",
            "item",
            "status",
            "item_nr "
        )

    def get_item_nr (self, obj):
        obj.item_nr = Items.objects.filter(item_id=self.context.get(id)).count()
        return obj.item_nr 

This is the error that I get:

Got AttributeError when attempting to get a value for field item_nr on serializer WebsiteSerializer. The serializer field might be named incorrectly and not match any attribute or key on the URL instance. Original exception text was: 'URL' object has no attribute 'item_nr '.

Upvotes: 0

Views: 2202

Answers (1)

xssChauhan
xssChauhan

Reputation: 2848

items_nr will be a SerializerMethodField not IntegerField The field will be automatically assigned data type based on what you return in get_item_nr.

class WebsiteSerializer(serializers.Serializer):
    item_nr = serializers.SerializerMethodField()

    class Meta:
        model = URL
        fields = (
            "id",
            "item",
            "status",
            "item_nr "
        )

    def get_item_nr (self, obj):
        obj.item_nr = Items.objects.filter(item_id=self.context.get(id)).count()
        return obj.item_nr 

Upvotes: 1

Related Questions