【问题标题】:Django get all ManyToMany relationships of an objectDjango获取对象的所有ManyToMany关系
【发布时间】:2016-11-30 19:08:57
【问题描述】:

我所有的模型都与其他模型和它们自己有几个多对多关系,它们都有一个“直通”表

假设我有模型 A ,它有一个 ManyToManyField 和模型 BC,我们还要考虑字段名称与相关模型相同

我的模型 D 有一个 ManyToManyField 和模型 A

现在,我想要获取与 BCD 类的 A 对象相关的所有对象

这是我尝试过的:

a1 = A.objects.get(pk = 1)
#Get all B objects related to A
a1.b.all()
#Get all C objects related to A
a1.c.all()
#Get all D objects related to A but from D class because that's where the field is
#Raises error 'ManyToManyDescriptor' object has no attribute 'all'
D.a.all(pk=1)

实际模型可以在here 找到(我的问题是 Pessoa 和 CCir)。

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    您可以使用a.d_set.all() 来获得反向关系,或者使用您提供的代码:

    obj = Pessoa.objects.get(pk=1) # get the object
    obj.ccir_set.all()
    

    您也可以考虑为您的 m2m 模型提供 related_name

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      相关资源
      最近更新 更多