[英]Django intersection of ManyToMany using Through model
我有兩個使用直通模型具有多對多關系的模型。
class Person(Model):
departments = ManyToManyField('Department', through='DepartmentStaff')
class Department(Model):
id = ...
class DepartmentStaff(Model):
staff_member = ForeignKey(Person, on_delete=CASCADE)
department = ForeignKey(Department, on_delete=CASCADE)
experience = DurationField()
我想檢查 2 Person 對象是否至少共享一個部門。 例如,如果p1
在部門d1
和d2
,而p2
在部門d2
和d3
,那么他們都在d2
工作,輸出應該是True
我知道我不能做這樣的事情
>>> p1.departments.intersection(p2.departments).exists()
...
AttributeError: 'ManyRelatedManager' object has no attribute 'query'
因為我使用的是直通關系。 檢查 2 個到 ManyToMany 查詢集是否包含至少一個相同元素的最佳方法是什么?
也許是這樣的?
DepartmentStaff.objects.filter(staff_member='p1', department__in=DepartmentStaff.objects.filter(staff_member='p2'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.