【问题标题】:Ways to shorten relation chain between objects缩短对象之间关系链的方法
【发布时间】:2013-09-05 08:36:54
【问题描述】:

例如我有这样的代码

class Product(models.Model):
    ...
    @property
    def review_count(self):
        return Review.objects.filter(order__product_id=self.id, published=True).count

class Order(models.Model):
    product = models.ForeignKey(Product)

class Review(models.Model):
    order = models.ForeignKey(Order)
    published = models.BooleanField(default=False)

而且我经常需要显示每个产品的评论数量。 我找到了方法 -

  1. property review_count - 看起来不错,但在 Product 对象集上速度很慢。
  2. 使用 .extra 方法进行注释 - 它更快,但需要额外的 SQL(我认为,我不能简单地使用注释,因为已发布 = True 对审查对象进行过滤)。

我认为,如果我在评论模型中使用 fk 到 Product 的附加字段“产品”,我将可以轻松快捷地获得一组产品,但在这种情况下,字段“产品”将依赖于字段“订单” ,我认为这不利于规范化。

P.S.:一个订单可能很少有评论 - 没关系。以及与评论相关的订单,以检查一个订单没有太多评论 - 审核问题。

请帮帮我,我该如何改进这个方案,以便更快、更轻松地获得对产品的评论次数

【问题讨论】:

    标签: django django-models foreign-key-relationship


    【解决方案1】:

    不知道你为什么说不能使用annotate()方法,因为需要过滤。这不仅受支持,而且文档中的explicitly described 也受支持。

    Product.objects.filter(order__review__is_published=True).annotate(Count('order__review'))
    

    【讨论】:

    • 我需要集合中的所有产品,不仅有评论,而且可以使用:Product.objects.annotate(Count('order__review'), Q(order__review__is_published=True)) 谢谢!
    猜你喜欢
    • 2016-02-08
    • 2011-03-08
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 2013-07-11
    • 1970-01-01
    相关资源
    最近更新 更多