I am trying to add a additional field to my modelviewset. For example, if I have 1 parent and 3 children objects, I would like parent viewset json to look like. To get the count of the children I can do something like
children = Child.objects.filter(parent.id=).count()
, but I'm not sure how to get the parent id inside the view set.
[
{
"id": 1,
"name": "parent1",
"child_count": 3
}
]
models.py
class Parent(models.Model):
name = models.CharField(max_length=100)
class Child(models.Model):
name = models.CharField(max_length=100)
parent = models.ForeignKey("Parent", on_delete=models.CASCADE)
views.py
class ParentViewSet(viewsets.ModelViewSet):
serializer_class = ParentSerializer
children = Child.objects.filter() # ??
def get_queryset(self):
queryset = Parent.objects.all().annotate(child_count=) # ??
return queryset
serializers.py
class ParentSerializer(serializers.ModelSerializer):
child_count = serializers.IntegerField()
class Meta:
model = Parent
fields = ["id", "name", "child_count"]
CodePudding user response:
There may be a shorthand way to get this count- however a SerializerMethodField is pretty straightforward.
class ParentSerializer(serializers.ModelSerializer):
child_count = serializers.SerializerMethodField()
class Meta:
model = Parent
fields = ["id", "name", "child_count"]
def get_child_count(self):
return Child.objects.filter(parent=self.get_object()).count()