Reputation: 1054
I am trying to define some ManyToMany relations in Django, but I have an error when I try to create related objects.
My models.py :
class PerfumeBrand(models.Model):
class Meta:
verbose_name = "Marque de parfum"
verbose_name_plural = "Marques de parfum"
name = models.CharField(max_length=32)
def __str__(self):
return self.person.first_name + ' ' + self.person.last_name.upper() + ': ' + self.name
class Person(models.Model):
class Meta:
verbose_name = "Personne"
verbose_name_plural = "Personnes"
first_name = models.CharField(max_length=32, )
last_name = models.CharField(max_length=32)
email = models.EmailField(unique=True)
# Here is the ManyToMany relation
perfume_brands = models.ManyToManyField(PerfumeBrand)
The problem is that when I try to save a PerfumeBrand object in my database, I get this error :
AttributeError at /admin/visualize/perfumebrand/add/
'PerfumeBrand' object has no attribute 'person'
I tried to save both in code and admin panel, the same error occurs.
As this is the first time I need a ManyToMany relation in a Django project, I am a bit confused, and I didn't find any solution to my problem.
Have you any idea ?
Upvotes: 1
Views: 2068
Reputation: 1981
On the PerfumeBrand
object, you have declared this
def __str__(self):
return self.person.first_name + ' ' + self.person.last_name.upper() + ': ' + self.name
But person
is not an attribute of PerfumeBrand
. That function should be under the Person
class (with some changes before) and you should use something like the following in the PerfumeBrand
class:
def __str__(self):
return self.name
Upvotes: 1