以下是相关模型:
class WhatToWearCandidates(models.Model):
profile = models.ForeignKey(Profile, null=False, blank=False, related_name="outfit_candidates")
look = models.ForeignKey(StyleLook, null=False, blank=False, related_name="outfit_candidates")
class StyleLook(models.Model):
# Non important attributes
class LookItem(models.Model):
look = models.ForeignKey(StyleLook, null=False, blank=False, related_name="lookitems")
item = models.ForeignKey(Product, null=False, blank=False, related_name="looks")
我将解释这一点,每个WhatToWearCandidates都有一个StyleLook和Profile,我们为每个配置文件显示正确的外观。 StyleLook只包含有关自身的详细信息。
每个StyleLook都由Products组成,在表LookItem中我们连接哪些StyleLooks包含哪些产品。
问题:我正在尝试有效地收集包含4个或更少产品的WhatToWearCandidates。
我正在尝试使用django的annotate()
类
all_candidates = WhatToWearCandidates.objects.filter(
look__lookitems__item__assignment=assignment.id, # This is to filter based on Products that belong in the current Assignment
profile_id=1, # Example profile
look_id=15 # Testing with 1 single look for the proper profile
).values('look_id').annotate(lcount=Count('look__lookitems'))
从调试器all_candidates
打印到[{'look__id': 15L, 'lcount': 1}]
。我知道这个外观包含6个产品,所以我希望lcount等于6。
要仔细检查,我尝试了StyleLook
的类似查询。
StyleLook.objects.filter(id__in=[15]).values('id').annotate(lcount=Count('lookitems'))
返回[{'id': 15L, 'lcount': 6}]
。
我做错了什么?如何在lcount
查询中将WhatToWearCandidates
等于6?
答案 0 :(得分:0)
我认为您可能在某个模型中遇到default ordering的问题。尝试将.order_by()
添加到查询的末尾:
all_candidates = WhatToWearCandidates.objects.filter(
look__lookitems__item__assignment=assignment.id,
profile_id=1,
).values('look_id').annotate(lcount=Count('look__lookitems')).order_by()