假设我有以下模型
class Tag(models.Model):
tag = models.CharField(max_length=128)
class Entry(models.Model):
...
tags = models.ManyToManyField(Tag, related_name='entries')
...
class Option(models.Model):
...
tags = models.ManyToManyField(Tag, related_name='options')
如何获取在给定Entry实例的标记集中至少包含2个标记的Option实例的查询集?
答案 0 :(得分:1)
这是你需要的吗?
from django.db.models import Count
options = Option.objects.filter(tags__in=entry.tags.all())
options = options.annotate(tag_count=Count('tags'))
options = options.filter(tag_count__gte=2)