簡體   English   中英

使用Through模型的ManyToMany的Django交集

[英]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在部門d1d2 ,而p2在部門d2d3 ,那么他們都在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM