I am working on a project with Django, Postgres. I typed that:
JavaScript
x
4
1
user_test = User.objects.first()
2
food_test = Food.objects.first()
3
user.food.add(food_test)
4
When I type that:
JavaScript
1
2
1
user.food
2
I got that:
JavaScript
1
2
1
<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7471bd30>
2
Then if I type that:
JavaScript
1
2
1
user.food.name
2
I got that:
JavaScript
1
2
1
AttributeError: 'ManyRelatedManager' object has no attribute 'name'
2
Whereas the field name exists.
Models.py:
JavaScript
1
14
14
1
class Food(models.Model):
2
name = models.CharField(max_length=1000, default="default", null=True)
3
4
def __str__(self):
5
return self.name
6
7
class User(models.Model):
8
food = models.ManyToManyField(Food)
9
first = models.CharField(max_length=1000, default="default", null=True)
10
11
def __str__(self):
12
return self.first
13
14
Advertisement
Answer
M2M relationship means – you have many objects.
user.food.name
get attrbute name
from M2M manager.
Probably you mean user.food.all().name
– this code get attrbute name
of Queryset.
Of course, I understand. You want user.food.first().name
– this get name
of first food if it exists or exception again, if foodQueryset
contains Nothing.