3

模型.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')

这是我的models.py。当我运行 syncdb 时,我收到此错误:

CommandError: One or more models did not validate:

app_quora.questioncomment: Accessor for field 'comment_author' clashes with rela
ted field 'MyUser.written_comments'. Add a related_name argument to the definiti
on for 'comment_author'.
app_quora.questioncomment: Reverse query name for field 'comment_author' clashes
 with related field 'MyUser.written_comments'. Add a related_name argument to th
e definition for 'comment_author'.
app_quora.questioncomment: Accessor for m2m field 'users_voted' clashes with rel
ated m2m field 'MyUser.voted_comments'. Add a related_name argument to the defin
ition for 'users_voted'.
app_quora.questioncomment: Reverse query name for m2m field 'users_voted' clashe
s with related m2m field 'MyUser.voted_comments'. Add a related_name argument to
 the definition for 'users_voted'.
app_quora.answercomment: Accessor for field 'comment_author' clashes with relate
d field 'MyUser.written_comments'. Add a related_name argument to the definition
 for 'comment_author'.
app_quora.answercomment: Reverse query name for field 'comment_author' clashes w
ith related field 'MyUser.written_comments'. Add a related_name argument to the 
definition for 'comment_author'.
app_quora.answercomment: Accessor for m2m field 'users_voted' clashes with relat
ed m2m field 'MyUser.voted_comments'. Add a related_name argument to the definit
ion for 'users_voted'.
app_quora.answercomment: Reverse query name for m2m field 'users_voted' clashes 
with related m2m field 'MyUser.voted_comments'. Add a related_name argument to t
he definition for 'users_voted'.

好吧,错误告诉我为“comment_author”和“users_voted”添加“related_name”,我已经这样做了!!。我在stackoverflow上查找了类似的问题,但通常问题是人们没有这个“related_name”来冲突字段。

我添加了此字段,但仍然收到此错误...有人可以解释原因吗?

谢谢 :(((

4

1 回答 1

3

您看到的问题是由于模型中的ForeignKeyandManyToManyField字段BaseComment。因为它是一个抽象模型,所以 django 不会为它创建表。

QuestionComment但是,继承字段的派生模型AnswerComment会尝试在模型中添加由related_name( written_comments, voted_comments)定义的相同字段MyUser。因为您只能拥有一个具有相同名称的字段,所以它会给您这些错误。

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

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

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

于 2013-08-14T06:10:19.210 回答