如何在多对多 Django 中列出对象

Reg*_*lva 2 django many-to-many django-queryset

考虑这个模型

class Dealership(models.Model):
    dealership = models.CharField(max_length=50)

class Ordered(models.Model):
    customer = models.ForeignKey("Customer")
    dealership = models.ManyToManyField("Dealership")
    status = models.CharField(max_length=2, choices=status_list, default='p')
Run Code Online (Sandbox Code Playgroud)

我试试

$ ./manage.py shell
>>> from new_way.core.models import Ordered, Dealership
>>> q = Ordered.objects.all()[:5]
>>> [i.dealership for i in q.dealership.all]
Run Code Online (Sandbox Code Playgroud)

并产生错误

Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'QuerySet' object has no attribute 'dealership'
Run Code Online (Sandbox Code Playgroud)

如何返回

Ordered.dealership.dealership
Run Code Online (Sandbox Code Playgroud)

所有经销商均已订购。

Bra*_*don 5

你非常接近:

改变:

[i.dealership for i in q.dealership.all]
Run Code Online (Sandbox Code Playgroud)

到:

[dealership for dealership in q.dealership.all()]
Run Code Online (Sandbox Code Playgroud)

这是我的模型在一个项目上的 M2M 关系之一的示例输出,它演示了您应该从列表理解中看到的内容。shared_with是一个名为 的模型的 M2M 字段Profile

>>> from polls.models import Poll
>>> polls = Poll.objects.all()
>>> for p in polls:
...   print([sw for sw in p.shared_with.all()])
... 
[<Profile: kerri>]
[<Profile: kerri>]
[]
[<Profile: jake>, <Profile: kerri>]
[<Profile: jake>, <Profile: kerri>]
[<Profile: jake>, <Profile: kerri>]
[<Profile: btaylor>]
[<Profile: jake>, <Profile: kerri>]
Run Code Online (Sandbox Code Playgroud)


Rah*_*pta 5

它应该是:

q.dealership.all() #gives a list of objects 
Run Code Online (Sandbox Code Playgroud)

您可以直接执行此操作,而不是使用列表理解(在上面的答案中)。

示例:(摘自文档

from django.db import models

class Publication(models.Model):
    title = models.CharField(max_length=30)

    def __str__(self):              # __unicode__ on Python 2
        return self.title

    class Meta:
        ordering = ('title',)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

    def __str__(self):              # __unicode__ on Python 2
        return self.headline

    class Meta:
        ordering = ('headline',)
Run Code Online (Sandbox Code Playgroud)

创建几个出版物:

p1 = Publication(title='The Python Journal')
p1.save()
p2 = Publication(title='Science News')
p2.save()
p3 = Publication(title='Science Weekly')
p3.save()
Run Code Online (Sandbox Code Playgroud)

现在,创建一个Article并将其Article与 a关联Publication

a1 = Article(headline='NASA uses Python')
a1.save()
a1.publications.add(p1, p2)
a1.publications.add(p3)

a1.publications.all()
[<Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
Run Code Online (Sandbox Code Playgroud)