Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

I have two classes with a ManyToMany relationship. I'd like to select one from the first class and access the fields of the related class. It seems like this should be easy. For example:

class Topping(models.Model):
  name = models.CharField(max_length=40)

class Pizza(models.Model):
  name = models.CharField(max_length=40)
  toppings = models.ManyToManyField(Topping)

So I'd want to do something like:

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

But this doesn't work for me. Thanks for any help.

like image 497
Mitch Avatar asked May 29 '09 21:05

Mitch


People also ask

How fetch data from many-to-many field in Django?

A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.

How does Django handle many-to-many relationship?

Django will automatically generate a table to manage many-to-many relationships. You might need a custom “through” model. The most common use for this option is when you want to associate extra data with a many-to-many relationship.

How do you update many-to-many fields?

You need to use . set() or . add() for updating a M2M field.

Is there a list field in Django?

These field classes are only maintained for legacy purposes. They aren't recommended as comma separation is a fragile serialization format. For new uses, you're better off using Django 3.1's JSONField that works with all database backends.


1 Answers

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.

like image 99
Paolo Bergantino Avatar answered Oct 23 '22 15:10

Paolo Bergantino