Django两个自我引用的外键

时间:2015-09-17 18:30:42

标签: python django django-1.7

Django 1.7中的一个简单的应用程序。是表示链接列表元素的模型:

class TrainingUserWordSetItem(models.Model):
    training_set = models.ForeignKey(TrainingUserWordSet)
    user_word = models.ForeignKey(UserWord)
    prev_item = models.ForeignKey("TrainingUserWordSetItem", null=True, default=None)
    next_item = models.ForeignKey("TrainingUserWordSetItem", null=True, default=None)

迁移时出现错误:

hellodict.TrainingUserWordSetItem.next_item: (fields.E304) Reverse accessor for 'TrainingUserWordSetItem.next_item' clashes with reverse accessor for 'TrainingUserWordSetItem.prev_item'.
        HINT: Add or change a related_name argument to the definition for 'TrainingUserWordSetItem.next_item' or 'TrainingUserWordSetItem.prev_item'.
hellodict.TrainingUserWordSetItem.prev_item: (fields.E304) Reverse accessor for 'TrainingUserWordSetItem.prev_item' clashes with reverse accessor for 'TrainingUserWordSetItem.next_item'.
        HINT: Add or change a related_name argument to the definition for 'TrainingUserWordSetItem.prev_item' or 'TrainingUserWordSetItem.next_item'.

如何制作两个自引用外键字段?

更新

帮助使用related_name =' +':

class TrainingUserWordSetItem(models.Model):
    training_set = models.ForeignKey(TrainingUserWordSet)
    user_word = models.ForeignKey(UserWord)
    prev_item = models.ForeignKey("TrainingUserWordSetItem", null=True, default=None)
    next_item = models.ForeignKey("TrainingUserWordSetItem", null=True, default=None, related_name='+')

1 个答案:

答案 0 :(得分:5)

你实际上可能完成了你在一个领域尝试的东西。我相信这会奏效:

next_item = models.ForeignKey('self', null=True, default=None, related_name='prev_item')

注意使用'self';根据{{​​3}},To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self').

此外,我建议尝试使用OneToOneField而不是ForeignKey,假设每个项目只有一个前一个项目和一个下一个项目。