How to return objects num many to many Django

2

Consider the template

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

I've tried

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

You generated the following error:

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

How to return

Ordered.dealership.dealership

all dealership by Ordered.

    
asked by anonymous 16.06.2015 / 04:39

1 answer

2

The error says that 'QuerySet' object has no attribute 'dealership' . You're actually doing this:

ordens = Ordered.objects.all().dealership.all()

For the code to work correctly you should loop the orders and then make a second loop.

lista = []
ordens = Ordered.objects.all()
for ordem in ordens:
    for o in ordem.dealership.all():
        lista.append(o.dealership)

or

lista = [o.dealership for o in ordem.dealership.all() for ordem in Ordered.objects.all()]
    
16.06.2015 / 05:32