access an attribute of a target model in a many-to-many relationship

190 views
Skip to first unread message

Issa N'golo Coulibaly

unread,
Nov 29, 2022, 7:13:57 PM11/29/22
to Django users
Hi, when I try to access an attribute of a target model in a many to many relationship, I get an error : AttributeError: 'ManyRelatedManager' object has no attribute 'full_name'
so, how to do ?

An exemple:

Class Person(models.Model):
    full_name = models.CharField(max_length=200)
    email = models.EmailField()

Class Message(models.Model):
   
    person = models.ManyToManyField(Person)
    title = models.CharField(max_length=200)
    body = models.TextField()
    
I have already created a Person object and Message object to the database:
   
mess = Message.objects.get(title="sos")
print(mess.person.email) // the error occurs here.

Ryan Nowakowski

unread,
Nov 29, 2022, 10:04:01 PM11/29/22
to django...@googlegroups.com
With a ManyToManyField field you're saying that a message can have many people and a person can have many messages. So:

mess.person.email

... doesn't make sense. You'll need to filter for the person whose email you want. Ex:

mess.person.first().email



By the way, the Django documentation recommends[1] that a ManyToManyField be plural to avoid this confusion. So:

people = models.ManyToManyField(Person)

...instead of:

person = models.ManyToManyField(Person)

[1] https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/#many-to-many-relationships

Viper Code

unread,
Nov 30, 2022, 2:06:39 AM11/30/22
to django...@googlegroups.com
mess = Message.objects.get(title="sos")
// print(mess.person.email) // the error occurs here.

emails = []
for m in mess:
    emails.append(m.email)

print(emails)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/544808b8-d60f-4020-a7f6-eb415dd37fdbn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages