0

i use a table Bid in this table have multi fields and a field named user other hand have a Dealer table that save users in Dealer_serializer i have a bids_count serializer Method Field that return each user count in Bid table i want use annotate instead of loop over filter! to get each user how many in Bid Table. if my idea not true explain me what exactly doing annotation?

class Dealer(User):
    car_exhibition = models.CharField(max_length=200, blank=True, null=True)
    phone = models.CharField(max_length=11, blank=True, null=True)
    city = models.ForeignKey('locations.City', blank=True, null=True)
    address = models.TextField(max_length=500)

class Bid(models.Model):
    auction = models.ForeignKey('Auction')
    user = models.ForeignKey('users.User')
    step = models.BigIntegerField()
    price = models.BigIntegerField()

created_time = models.DateTimeField(auto_now=True)
3
  • 1
    It's better to provide a code snippet rather than describing it. Please paste your models. Commented Dec 17, 2018 at 6:20
  • paste models the end of comments Commented Dec 17, 2018 at 6:47
  • Dealer inherit from django user table that have username , id, ... Commented Dec 17, 2018 at 6:54

1 Answer 1

1

I can't find the relation of your Dealer with Bid. But for User you can use annotation:

User.objects.annotate(bids_count=Count('bid')).values('id', 'bids_count')

As a result you will have:

<QuerySet [{'id': 1, 'bids_count': 3}, {'id': 2, 'bids_count': 10}, ..., >

Where id is user_id and bid_count is how many Bids are related to User with that id. I hope this is what you are going to achieve. Please comment in case of any questions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.