我的models.py看起来像
class RelevanceRelation(TimeStampable, SoftDeletable, models.Model):
relevance_type = models.ForeignKey(
RelevanceType,
on_delete=models.CASCADE,
related_name="relevance_relations"
)
name = models.CharField(max_length=256,
verbose_name="Relevance Relation Name")
def __str__(self):
return self.name
class RelevanceRelationValue(TimeStampable, SoftDeletable, models.Model):
entity = models.ForeignKey(
Entity, on_delete=models.CASCADE,
related_name="relevance_relation_values"
)
relevance_relation = models.ForeignKey(
RelevanceRelation,
on_delete=models.CASCADE,
related_name="values"
)
name = models.CharField(max_length=256,
verbose_name="Relevance Relation Value")
def __str__(self):
return self.name
我有两个查询集
q1 = RelevanceRelationValue.objects.filter(entity=<int>)
q2 = RelevanceRelation.objects.filter(relevance_type=<int>)
现在有一种方法可以找到q1
和q2
的交集,即我不会显示q2
在{{ 1}}
例如:
id
答案 0 :(得分:1)
您可以执行额外的过滤:
q1 = RelevanceRelationValue.objects.filter(entity=some_value1).values('relevance_relation')
q2 = RelevanceRelation.objects.filter(
relevance_type=some_value2,
id__in=q1
)
但是仅对相关模型进行过滤更有意义,所以:
RelevanceRelation.objects.filter(
values__entity=some_value1,
relevance_type=some_value2
).distinct()
在这里,我们得到RelevanceRelation
为relevance_type
的所有some_value2
,并且与{{ 1}}。