Django 的两个自引用外键

Django two self-referential foreign key

在 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='+')

您实际上可以在一个字段上完成您正在尝试的事情。我相信这会奏效:

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

注意'self'的使用;根据Django documentationTo create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self').

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