[英]Django 1.6 ORM count subset of related items
我有這些模特
class BlogEntry(models.Model):
tags = models.ManyToMany(Tag, ...)
...
class Tag(models.Model):
...
和標簽的子集:
tag_list = list(*some tag objects*) # can refactor to queryset
我需要獲取標簽列表中每個BlogEntry的標簽數量,因此如下所示:
# Non-working code ahead
BlogEntry.objects.annotate(match=Count(tags__in=tag_list))
我有這段代碼可以正常運行
# working code ahead
for entry in BlogEntry.objects.all():
match = len(set(entry.tags.all()).intersection(tag_list))
但是我覺得在python中而不是在數據庫中進行計數和相交會在以后造成性能問題。
請參閱有關annotate()和filter()子句的順序的文檔。
如該部分所述,如果在注釋之前進行過濾,則注釋將僅包括過濾器匹配的元素。 所以:
BlogEntry.objects.filter(tags__in=tag_list).annotate(match=Count(tags))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.