Django' related_name'用户验证错误

时间:2014-03-29 17:05:52

标签: django

在我的项目中,当我添加一个使用ForeignKey w / User和' related_name'的模型时,我在models.py中收到错误。例如:

class Follow(models.Model):
follower = models.ForeignKey('User', related_name='id_of_the_follower')
who_following = models.ForeignKey('User', related__name='id_of_the_person_being_followed')
pubdate = models.DateTimeField(default=timezone.now)

class Meta:
    ordering = ['-pubdate']

我得到的错误是:

lobby.follow: 'follower' has a relation with model User, which has either not been installed or is abstract.
lobby.follow: 'who_following' has a relation with model User, which has either not been installed or is abstract.

我导入了我的用户数据库:     来自django.contrib.auth.models导入用户

Models.py可以很好地验证我的其他模型,这些模型将User作为ForeignKey但不使用' related_name'但是当我有一个related_name时,它一直让我犯错。

1 个答案:

答案 0 :(得分:1)

首先:你已经写过" related_name" (" who_following" field)关键字带有双下划线。这是错的!


只要您使用" django.contrib.auth"你应该像这样引用用户模型:

class Follow(models.Model):
    follower = models.ForeignKey('auth.User',
        related_name='id_of_the_follower')
    who_following = models.ForeignKey('auth.User',
        related_name='id_of_the_person_being_followed')

或者您可以明确地引用模型用户:

from django.db import models
from django.contrib.auth.models import User

class Follow(models.Model):
    follower = models.ForeignKey(User,
        related_name='id_of_the_follower')
    who_following = models.ForeignKey(User,
        related_name='id_of_the_person_being_followed')

但是,如果你想引用"用户"从项目中的其他应用程序模型,您应该执行以下操作:

class Follow(models.Model):
    follower = models.ForeignKey("yourappname.User",
        related_name='id_of_the_follower')
    who_following = models.ForeignKey("yourappname.User",
        related_name='id_of_the_person_being_followed')