models.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”。
我添加了这些字段,但仍然收到此错误...有人可以解释原因吗?
谢谢:((
答案 0 :(得分:3)
您看到的问题是由于ForeignKey
模型中的ManyToManyField
和BaseComment
字段。因为它是一个抽象模型,所以django不会为它创建一个表。
但是,继承字段的派生模型QuestionComment
和AnswerComment
会尝试添加related_name
(written_comments
,voted_comments
)定义的相同字段MyUser
模型。因为您只能有一个具有相同名称的字段,所以会为您提供这些错误。
解决方案是不要将BaseComment
作为抽象模型,让它拥有自己的表/模型。
或者,您可以在派生模型中添加这些字段。
您也可以尝试不指定related_name
并让django决定名称,但我不确定这是否有效。