Django:ManyToManyField未定义错误

1 投票
2 回答
3275 浏览
提问于 2025-04-18 09:02

我一直在尝试编辑django-userena中的用户资料,其他部分都没问题,就是我的ManyToManyFields(多对多字段)出了点状况。我设置了以下模型:

class MyProfile(UserenaBaseProfile):
    user = models.OneToOneField(User,unique=True,  
                        verbose_name=_('user'),related_name='my_profile')
    favourite_snack = models.CharField(_('favourite snack'),max_length=5) 
    firstname = models.CharField(_('username'), max_length=55)
    lastname = models.CharField(_('lastname'), max_length=66)
    industry = models.CharField(_('industry'), max_length=190)
    occupation = models.CharField(_('occupation'), max_length=140)
    bio = models.TextField(_('bio'))
    phone = models.CharField(_('phone'), max_length=10)
    skills = models.ManyToManyField(Skills)
    Interests = models.ManyToManyField(Interests)
    website = models.URLField()

class Skills(models.Model):
    skillName = models.CharField(max_length=80)

class Interests(models.Model):
    interestName = models.CharField(max_length=140)

当我同步数据库时,出现了以下错误:

 File "/pathtodjango/bin/app/accounts/models.py", line 17, in MyProfile
    skills = models.ManyToManyField(Skills)
NameError: name 'Skills' is not defined

2 个回答

4

问题在于你在定义模型类 Skills 之前就引用了它。要注意,Python 不像 JavaScript 那样支持函数(类)提升。 所以你的代码应该像这样:

class Skills(models.Model):
    skillName = models.CharField(max_length=80)

class Interests(models.Model):
    interestName = models.CharField(max_length=140)


class MyProfile(UserenaBaseProfile):
    user = models.OneToOneField(User,unique=True,  
                        verbose_name=_('user'),related_name='my_profile')
    favourite_snack = models.CharField(_('favourite snack'),max_length=5) 
    firstname = models.CharField(_('username'), max_length=55)
    lastname = models.CharField(_('lastname'), max_length=66)
    industry = models.CharField(_('industry'), max_length=190)
    occupation = models.CharField(_('occupation'), max_length=140)
    bio = models.TextField(_('bio'))
    phone = models.CharField(_('phone'), max_length=10)
    skills = models.ManyToManyField(Skills)
    Interests = models.ManyToManyField(Interests)
    website = models.URLField()
20

使用懒引用:

skills = models.ManyToManyField('Skills')

撰写回答