我对User和Post模型之间的ForeignKey关系有疑问。或者,当为自定义用户模型创建ForeignKey时,出现错误:
跟踪:
#CustomUserModel
class Usr(AbstractBaseUser):
username = models.CharField(max_length=30, validators=[
RegexValidator(
regex=USERNAME_REGEX,
message='Username must be alphanumeric or numbers',
code='invalid_username'
)
], unique=True)
objects = UsrManager()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
def has_perm(self, perm, obj=None):
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
# Simplest possible answer: Yes, always
return True
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
#Model with ForeignKey
class Posts(models.Model):
title = models.CharField(max_length=50, unique=True)
text = models.CharField(max_length=300)
author = models.OneToOneField(get_user_model() ... default=1, swappable=True, related_query_name='post', db_constraint=True, related_name='posts', on_delete=models.CASCADE)
错误页面: https://i.stack.imgur.com/0pyRq.png
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to a member function setCookie() on null
对于可能存在的代码缺陷和语法错误,我深表歉意。预先谢谢你!
编辑: 错误仅在管理员中发生,在Shell中有效
答案 0 :(得分:0)
OneToOneField表示一个用户只有一个帖子,而一个帖子只有一个用户 这增加了唯一约束。 您需要使用外键(是的,您不使用它)
author = models.ForeignKey(...)