Django“在定义“E”中添加相关的\u name参数

2024-04-25 23:53:03 发布

您现在位置:Python中文网/ 问答频道 /正文

模型.py

class BaseComment(models.Model):
    comment_author = models.ForeignKey(MyUser, related_name='written_comments')
    comment_content = models.CharField(max_length=500)
    comment_date = models.DateTimeField(auto_now_add=True)
    rating = models.IntegerField(default=0)
    users_voted = models.ManyToManyField(MyUser, related_name='voted_comments')

    class Meta:
        abstract = True
        ordering = ['-comment_date']        

    def __unicode__(self):
        return self.comment_author.email

class QuestionComment(BaseComment):
    question = models.ForeignKey(Question, related_name='comments')

class AnswerComment(BaseComment):
    answer = models.ForeignKey(Answer, related_name='comments')

这是我的模型.py. 运行syncdb时,出现以下错误:

^{pr2}$

好吧,这个错误告诉我要为“评论作者”和“用户投票”添加“相关名称”,我已经做了!!。我在stackoverflow上查过类似的问题,但通常问题是人们没有冲突字段的“相关名称”。在

我添加了这些字段,但仍然得到这个错误。。。有人能解释一下为什么吗?在

((谢谢:)


Tags: namepy模型truedatemodels错误comment
1条回答
网友
1楼 · 发布于 2024-04-25 23:53:03

您看到的问题是因为BaseComment模型中的ForeignKey和{}字段。因为它是一个抽象模型,django不为它创建表。在

然而,继承这些字段的派生模型QuestionComment和{}试图在MyUser模型中添加由related_namewritten_commentsvoted_comments)定义的相同字段。因为只有一个字段具有相同的名称,所以会出现这些错误。在

一个解决方案是不要将BaseComment作为抽象模型,而让它有自己的表/模型。在

或者,可以在派生模型中添加这些字段。在

您也可以尝试不指定related_name,让django决定名称,但我不确定这是否有效。在

相关问题 更多 >