Home > Software design >  Get number of objects in serializer where foreign key field is x
Get number of objects in serializer where foreign key field is x

Time:11-03

Suppose

class ABC(models.Models):
    ...
    id = models.SlugField(...)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    ...

Now i want something like

   [{id: adfsdd, no_of_user_objects: 5}, {id: gdfvsdf, no_of_user_objects: 0}, {id: ergthf, no_of_user_objects: 2}]

How do i achieve this?

CodePudding user response:

Model method for getting the number of users having the same slug id:

class ABC(models.Models):
    ...
    id = models.SlugField(...)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    ...

    @property # for using in serializer
    def no_of_user_objects(self):
        return ABC.objects.filter(id=self.id).count()

And in your serializer have a custom serializer for the queryset serializer:

class ABDSerializer(serializers.ModelSerializer):
     class Meta:
        model = ABC
        fields = ['id', 'no_of_user_objects']

# in your view
queryset = ABC.objects.distinct('id')
serializer = ABDSerializer(queryset, many=True)
print(serializer.data)
# get you    [{id: adfsdd, no_of_user_objects: 5}, {id: gdfvsdf, #no_of_user_objects: 0}, {id: ergthf, no_of_user_objects: 2}]
  • Related