Tuesday, November 29, 2022

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

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)

Pada tanggal Rab, 30 Nov 2022 07.13, Issa N'golo Coulibaly <coulibalyissa956@gmail.com> menulis:
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.

--
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+unsubscribe@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.

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAHKnc1xvh3qtnOtg1T-KPMGFZpPV3xUdW7q_AGvXCzhbgEOZeQ%40mail.gmail.com.

No comments:

Post a Comment