2
Consider the model
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 tried to
$ ./manage.py shell
>>> from new_way.core.models import Ordered, Dealership
>>> q = Ordered.objects.all()[:5]
>>> [i.dealership for i in q.dealership.all]
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.
I didn’t want to mix the posts, but on http://stackoverflow.com/a/30858064/802542 because it doesn’t work the way I did before? Do you have to use 2 loops anyway? But anyway it worked. Thank you.
– Regis Santos
Your code doesn’t work because you were trying to get an attribute from a
queryset
and not the object, so it was necessary to loop the filtered objects and then another loop of the field objectsmanytomanyfield
– Paulo
a manyTomany always works like this for iteration? Why didn’t I find this in the documentation?
– Regis Santos
@Regisdasilva always works like this, certainly has in the documentation the explanation, maybe it is not clear.
– Paulo
+1 I would just suggest making a
prefetch_related
to avoid an additional SQL query for each iteration of this loop (I think theprefetch_related
works forManyToManyField
, or I’m wrong?).– mgibsonbr
@Orion just one more thing:
print([o.dealership__address for o in order.dealership.all()])
orprint([o.dealership.address for o in order.dealership.all()])
was not. Did not return the address.– Regis Santos
@mgibsonbr I can’t tell you, I’ve never used
prefetch_related
, I’ll even take a look at the documentation later– Paulo
@Regisdasilva would not be
o.address
?– Paulo
@Orion think I’m missing rsrs Thanks Again.
– Regis Santos
@Orion It works yes! See that code in the Pastebin: I did the same query twice, for the same set of
4
Ordered
; without theprefetch_related
he did5
darlings (1
for theOrdered
s and1
for eachOrdered
returned by the first query - if they were1000
results he would make1000
darlings); with theprefetch_related
he just did2
darlings (1
for theOrdered
s and1
to find theDealership
s of all results at once - if they were1000
results would still be a single query). Significant difference in performance! :)– mgibsonbr