【发布时间】:2020-06-25 17:32:15
【问题描述】:
我希望我的 Comments 模型中的 user_image、email 和 name 字段继承自 UserProfile 模型。我尝试在我的 ForeignKey 字段中使用 UserProfile.profile_image 作为基类,但它显然没有用。我知道这是错误的,但任何替代方案都可以。
class UserProfile(AbstractUser):
username = None
bio = models.TextField(null=True, blank=True)
profile_image = models.FileField(upload_to="profile_pic", blank=True, null=True)
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments', null=True)
name = models.CharField(max_length=150)
user_image = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
email = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
body = models.TextField()
created_date = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_date']
def __str__(self):
return '{} comment made by {}'.format(self.body, self.name)
【问题讨论】:
-
实际上继承 AbstractUser 类只是为了提供用户资料信息是个坏主意。只需创建名为 UserProfile 的新模型(不要触摸 AbstractUser),并使 OneToOneField 指向 User 模型。在这里阅读更多:simpleisbetterthancomplex.com/tutorial/2016/11/23/…
标签: django django-models