【问题标题】:how use annotation Instead loop on filter如何在过滤器上使用注释而不是循环
【发布时间】:2018-12-17 06:19:57
【问题描述】:

我使用一个表 Bid 在这个表中有多个字段和一个名为 user 的字段另一方面有一个 Dealer 表,可以在 Dealer_serializer 中保存用户我有一个 bids_count 序列化器 Method 字段,它返回 Bid 表中的每个用户计数我想使用注释代替的循环过滤器!让每个用户在投标表中有多少。 如果我的想法不正确,请解释我到底在做什么注释?

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)

【问题讨论】:

  • 最好提供代码sn-p而不是描述它。请粘贴您的models
  • 粘贴模型结束cmets
  • Dealer 继承自 django 用户表,具有 username , id, ...

标签: django django-models


【解决方案1】:

我找不到您的DealerBid 的关系。但是对于User,你可以使用注解:

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

因此,您将拥有:

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

其中iduser_idbid_count 是与User 相关的Bidsid。 我希望这是您将要实现的目标。如有任何问题,请发表评论。

【讨论】:

    猜你喜欢
    • 2016-08-29
    • 1970-01-01
    • 2011-06-25
    • 2016-09-07
    • 1970-01-01
    • 2012-01-27
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多