Tuesday, November 29, 2022

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

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


On November 29, 2022 12:31:28 PM CST, Issa N'golo Coulibaly <coulibalyissa956@gmail.com> wrote:
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.

No comments:

Post a Comment