【问题标题】:Django intersection of ManyToMany using Through modelManyToMany的Django交集使用Through模型
【发布时间】:2020-03-28 11:29:57
【问题描述】:

我有两个使用直通模型具有多对多关系的模型。

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工作,而p2d2d3部门工作,那么他们都在d2工作,输出应该是True

我知道我不能这样做

>>> p1.departments.intersection(p2.departments).exists()
...
AttributeError: 'ManyRelatedManager' object has no attribute 'query'

因为我使用的是直通关系。检查 2 到 ManyToMany 查询集是否包含至少一个相同元素的最佳方法是什么?

【问题讨论】:

    标签: python django


    【解决方案1】:

    也许是这样的?

    DepartmentStaff.objects.filter(staff_member='p1', department__in=DepartmentStaff.objects.filter(staff_member='p2'))

    【讨论】:

    • 嗯,这里似乎总是返回一个空查询集,因为您使用 & on 的 2 个查询集是互斥的。
    • 这会失败,因为您使用 DepartmentStaff 作为过滤部门的查询集。代码引发 ValueError
    猜你喜欢
    • 2014-02-04
    • 2023-01-29
    • 2012-02-27
    • 2015-06-23
    • 1970-01-01
    • 2012-04-12
    • 2012-06-12
    • 1970-01-01
    • 2018-04-05
    相关资源
    最近更新 更多