RoyalBosS
RoyalBosS

Reputation: 440

Count objects on the basis of foreign key

Suppose

class Model1(models.Model):
    post = models.ForeignKey(Post,...)
    author = models.ForeignKey(User,...)
    ...

Now how do i get a list of model1 objects with author id and number of objects of model1 where author is author.

For Example

[{userid: 1, noofposts: 5}, {userid: 2, noofposts" 1}, ...]

I want to use that code in django serializers.

Thanks in Advance!

Upvotes: 0

Views: 76

Answers (1)

Uzzal H. Mohammad
Uzzal H. Mohammad

Reputation: 801

You can add e methodSerializrerField in the serializer and the method can return something like this to get the response you are expecting,

Model1.objects.values('author','post').annotate(noofposts=Count('posts')).order_by('-nooofposts')

Upvotes: 1

Related Questions