Django - 使用多个外键到同一个模型

时间:2017-01-17 12:54:11

标签: python django

我正在尝试对同一模型中的两个字段使用相同的外键,但是收到错误。

我正在尝试使用主要和次要通话用户,但我不确定如何在收到以下错误后格式化关系

class ManualRotas(models.Model):
    rota_name = models.CharField(max_length=200,choices=settings.ONCALL_ROTAS)
    primary_user = models.ForeignKey(User, unique=True, verbose_name="Primary OnCall Engineer")
    p_start_time = models.DateTimeField(verbose_name="Start Time")
    p_end_time = models.DateTimeField(verbose_name="End Time")
    secondary_user = models.ForeignKey(User, verbose_name="Backup OnCall Engineer", unique=True,blank=True,null=True)
    s_start_time = models.DateTimeField(blank=True,null=True, verbose_name="Start Time")
    s_end_time = models.DateTimeField(blank=True,null=True,verbose_name="Start Time")


ERRORS:
oncall.ManualRotas.primary_user: (fields.E304) Reverse accessor for 'ManualRotas.primary_user' clashes with reverse accessor for 'ManualRotas.secondary_user'.
        HINT: Add or change a related_name argument to the definition for 'ManualRotas.primary_user' or 'ManualRotas.secondary_user'.
oncall.ManualRotas.secondary_user: (fields.E304) Reverse accessor for 'ManualRotas.secondary_user' clashes with reverse accessor for 'ManualRotas.primary_user'.
        HINT: Add or change a related_name argument to the definition for 'ManualRotas.secondary_user' or 'ManualRotas.primary_user'.

WARNINGS:
oncall.ManualRotas.primary_user: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.
        HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.
oncall.ManualRotas.secondary_user: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.
        HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.

System check identified 4 issues (0 silenced).

1 个答案:

答案 0 :(得分:3)

您必须为related_name列定义不同的ForeignKeys。例如:

class ManualRotas(models.Model):
    primary_user = models.ForeignKey(User, related_name='related_primary_manual_roats', unique=True, verbose_name="Primary OnCall Engineer")
    #                            related names ^ v
    secondary_user = models.ForeignKey(User, related_name='related_secondary_manual_roats', verbose_name="Backup OnCall Engineer", unique=True,blank=True,null=True)
    # .... Other columns

请同时参考Django: reverse accessors for foreign keys clashing,其中说:

  

用于从相关对象返回到此关系的关系的名称。它也是related_query_name的默认值(用于目标模型的反向过滤器名称的名称)。有关完整说明和示例,请参阅相关对象文档。请注意,在抽象模型上定义关系时必须设置此值;当你这样做时,可以使用一些特殊的语法。

相关帖子: