Skip to content
Advertisement

Unable to use ManyToMany Field with Django and Postgres

I am working on a project with Django, Postgres. I typed that:

user_test = User.objects.first()
food_test = Food.objects.first()
user.food.add(food_test)

When I type that:

user.food

I got that:

<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7471bd30>

Then if I type that:

user.food.name

I got that:

AttributeError: 'ManyRelatedManager' object has no attribute 'name'

Whereas the field name exists.

Models.py:

class Food(models.Model):
    name = models.CharField(max_length=1000, default="default", null=True)

    def __str__(self):
        return self.name

class User(models.Model):
    food = models.ManyToManyField(Food)
    first = models.CharField(max_length=1000, default="default", null=True)
    
    def __str__(self):
        return self.first
  

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement