简体   繁体   中英

Django : ManyToMany relation error ( object has no attribute)

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 ?

PerfumeBrand类从不定义变量person ,只定义name

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM