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

How to list objects in many to many Django

考虑此模型

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')

我试试

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

并产生错误

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

如何return

Ordered.dealership.dealership

所有经销商按订单。

你非常接近:

变化:

[i.dealership for i in q.dealership.all]

至:

[dealership for dealership in q.dealership.all()]

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

>>> 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>]

应该是:

q.dealership.all() #gives a list of objects 

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

示例:(摘自docs

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',)

创建几个出版物:

p1 = Publication(title='The Python Journal')
p1.save()
p2 = Publication(title='Science News')
p2.save()
p3 = Publication(title='Science Weekly')
p3.save()

现在,创建一个 Article 并将 ArticlePublication 相关联:

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>]