Home > front end >  Count foreignkey objects in django
Count foreignkey objects in django

Time:01-06

suppose

class Product(models.Model):
    user = models.ForeignKey(User,...)
    ...

class Sold(models.Model):
    post = models.ForeignKey(post,...)
    buyer = models.ForeignKey(User,...)

Now how do i get no of items sold using User model Something like User.objects.all().annotate(nbuy=Count("?"))

Putting "sold" at place of "?" gives number of items user have bought. What should i do to get no of items user have sold?

CodePudding user response:

You can do it if you query the Sold model like so:

Sold.objects.values('buyer').annotate(nbuy=Count('buyer'))

# returns -> {'buyer': 1, 'nbuy': 23}

This returns the the user id and the number of Sale objects that exist with that user id.

CodePudding user response:

Technically User.objects.all().annotate(nbuy=Count("sold")) counts all the Sold objects linked to a user by a ForeignKey. If I understand your model correctly the link represents the buyer, so you get number of products a user has bought.

I suppose the user in your Productrepresents the user offering, i.e. selling the product, so User.objects.all().(nsold=Count("product")) would give you that number.

  •  Tags:  
  • Related