如何在多对多Django中列出对象
Posted
技术标签:
【中文标题】如何在多对多Django中列出对象【英文标题】:How to list objects in many to many Django 【发布时间】:2015-08-31 16:50:36 【问题描述】:考虑这个模型
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'
如何退货
Ordered.dealership.dealership
所有经销店均按订购。
【问题讨论】:
【参考方案1】:你很亲密:
变化:
[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>]
【讨论】:
回溯(最近一次调用最后一次):文件“Dealership
实例的列表。我不明白你在之前的评论中指的是什么。【参考方案2】:
应该是:
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
并将Article
与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>]
【讨论】:
回溯(最近一次调用最后一次):文件“以上是关于如何在多对多Django中列出对象的主要内容,如果未能解决你的问题,请参考以下文章
Django - 查询列表中的任何项目在多对多字段中的任何对象