Django外键to_field

时间:2015-07-10 23:45:39

标签: django django-models foreign-keys

我有两个模型 CustomUser 杂志,带有随机/唯一的slug字段。现在我想用slug字段的外键创建第三个模型(Article):

class CustomUser(AbstractBaseUser):
    slug = RandomSlugField(length=6, unique=True)
    ...

class Magazine(models.Model):
    slug = RandomSlugField(length=6, unique=True)
    name = models.CharField()

class Article(models.Model):
    magazine = models.ForeignKey(Magazine, to_field='slug')
    author = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='slug')

但是当我迁移数据库以创建Article模型时,我收到以下错误:

django.core.exceptions.FieldDoesNotExist: CustomUser has no field named 'slug'

但CustomUser显然有一个名为' slug'。

的字段

对于杂志模型,我没有收到此错误。 有谁知道出了什么问题?

我将这个包用于slug字段: https://github.com/mkrjhnsn/django-randomslugfield

编辑: 以下是完整的CustomUser模型:

class CustomUser(AbstractBaseUser, PermissionsMixin):
    slug = RandomSlugField(length=6, exclude_upper=True)
    username = models.CharField(
        _('username'), max_length=30,
        help_text=_('Required. 30 characters or fewer.'
                'Letters, digits and '
                '@/./+/-/_ only.'),
        validators=[
            validators.RegexValidator(r'^[\w.@+-]+$',
                                  _('Enter a valid username.'), 'invalid')
        ])
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)

    # email is our unique field for authentication
    email = models.EmailField(_('email address'), unique=True)

    is_staff = models.BooleanField(
        _('staff status'), default=False,
        help_text=_('Designates whether the user can log '
                    'into this admin site.')
        )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.')
        )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    profile = models.OneToOneField('UserProfile', blank=True, null=True,
                               related_name='user_profile')

    image = models.ImageField(default='images/noimage.jpg',
                          upload_to=settings.PROFILE_IMAGE_PATH,
                          max_length=255)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

1 个答案:

答案 0 :(得分:2)

删除数据库,除 init 以外的所有迁移并尝试