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

Visto 195 veces
Saltar al primer mensaje no leído

Issa N'golo Coulibaly

no leída,
29 nov 2022, 19:13:5729/11/22
a 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

no leída,
29 nov 2022, 22:04:0129/11/22
a 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

no leída,
30 nov 2022, 2:06:3930/11/22
a 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.
Responder a todos
Responder al autor
Reenviar
0 mensajes nuevos