我的问题的答案很可能是“这是你能做的最好的事情”,但我希望我只是看着这个太久而错过了一些东西......
参考这篇关于不对称关系的文章,我正在查看“相互朋友关系”查询。以下是文章中的模型:
class Person(models.Model):
name = models.CharField(max_length=100)
relationships = models.ManyToManyField('self', through='Relationship',
symmetrical=False,
related_name='related_to')
def get_friends(self):
return self.relationships.filter(
to_people__from_person=self,
from_people__to_person=self)
class Relationship(models.Model):
from_person = models.ForeignKey(Person, related_name='from_people')
to_person = models.ForeignKey(Person, related_name='to_people')
JOIN 查询中的get_friends()
结果。
我想做的查询是“关注person_A但不关注person_B的人”。多对多的关系消除了很多工作,只留下了我的一个简单的查询要求......所以我有这个:
person_A.relationships\
.filter(from_people__to_person=person_A)\
.exclude(from_people__to_person=person_B)
结果包含一个子查询:
SELECT `person`.`id` FROM `person`
INNER JOIN `relationship` ON (`person`.`id` = `relationship`.`to_person_id`)
INNER JOIN `relationship` T4 ON (`person`.`id` = T4.`from_person_id`)
WHERE (
`relationship`.`from_person_id` = 178
AND T4.`to_person_id` = 178
AND NOT (`person`.`id` IN (
SELECT U1.`from_person_id` FROM `relationship` U1
WHERE (U1.`to_person_id` = 191 AND U1.`from_person_id` IS NOT NULL)
))
)
这种排除查询是否意味着需要子查询,或者我只是错过了一些简单的调整?