[Fixed]-In Django, how do you retrieve a field of a many-to-many related class?

26👍

Try:

Pizza.objects.filter(name = 'Pizza 1')[0].toppings.all()[0]

It works for me (different models, but the idea is the same):

>>> Affiliate.objects.filter(first_name = 'Paolo')[0]
<Affiliate: Paolo Bergantino>
>>> Affiliate.objects.filter(first_name = 'Paolo')[0].clients
<django.db.models.fields.related.ManyRelatedManager object at 0x015F9770>
>>> Affiliate.objects.filter(first_name = 'Paolo')[0].clients[0]
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'ManyRelatedManager' object is unindexable
>>> Affiliate.objects.filter(first_name = 'Paolo')[0].clients.all()
[<Client: Bergantino, Amanda>]
>>> Affiliate.objects.filter(first_name = 'Paolo')[0].clients.all()[0]
<Client: Bergantino, Amanda>

For more on why this works, check out the documentation.

Leave a comment