【问题标题】:How to list objects in many to many Django如何在多对多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

所有经销店均按订购。

【问题讨论】:

    标签: django many-to-many django-queryset


    【解决方案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>]
    

    【讨论】:

    • 回溯(最近一次调用最后一次):文件“”,第 1 行,在 中 AttributeError:'QuerySet' 对象没有属性'dealership'
    • [x for x in Ordered().__dict__.keys()] ['modified_at', 'created_at', 'kiosk_id', '_state', 'vehicle_id', 'kit_optional_id', 'customer_id ', '状态', 'id']
    • 经销商不存在。但是 _state 存在。
    • 上面的代码应该给你一个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 并将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>]
    

    【讨论】:

    • 回溯(最近一次调用最后一次):文件“”,第 1 行,在 中 AttributeError:'QuerySet' 对象没有属性'dealership'
    猜你喜欢
    • 1970-01-01
    • 2013-09-19
    • 2018-10-05
    • 1970-01-01
    • 2019-04-12
    • 2012-09-16
    • 2021-10-24
    • 2020-09-22
    相关资源
    最近更新 更多