Reputation: 437
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 serializerWebsiteSerializer
. The serializer field might be named incorrectly and not match any attribute or key on theURL
instance. Original exception text was: 'URL' object has no attribute 'item_nr '.
Upvotes: 0
Views: 2202
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