我尝试将Comment
与User
模型关联,但不知何故该字段未在数据库中创建。当我尝试访问该页面时,显示以下错误:
(1054,"未知列' user_comments.user_id'在'字段列表'")
这些在models.py
:
class User(models.Model):
username = models.CharField(max_length=128)
password = models.CharField(max_length=128)
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
email = models.CharField(max_length=128)
date_joined = models.DateField(auto_now_add=True)
class Meta:
db_table = 'auth_user'
ordering = ('date_joined',)
class Comment(models.Model):
user = models.ForeignKey('auth.User', related_name='comments', on_delete=models.CASCADE)
content = models.CharField(max_length=256)
date_created = models.DateField(auto_now_add=True)
class Meta:
db_table = 'user_comments'
ordering = ('date_created',)
def __str__(self):
return self.content
def save(self, *args, **kwargs):
content = self.content
super(Comment, self).save(*args, **kwargs)
如果我将user
变量命名为user_id
,则会在管理面板中创建新user_id_id
时显示错误,说明Comment
未找到。
**更新**
我删除了整个数据库,删除了db_table
选项,因此创建了user_id
。但是现在,在创建新的Comment
时,以下内容:
IntegrityError at /admin/api/comment/add/
(1452, 'Cannot add or update a child row: a foreign key constraint fails (`softwarestore`.`api_comment`, CONSTRAINT `api_comment_user_id_14315666_fk_api_user_id` FOREIGN KEY (`user_id`) REFERENCES `api_user` (`id`))')
答案 0 :(得分:1)
您是否尝试过简单地替换以下内容:
user = models.ForeignKey('auth.User', related_name='comments', on_delete=models.CASCADE)
与
user = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE)
并运行makemigrations?