我正在尝试对同一模型中的两个字段使用相同的外键,并且出现错误。
我正在尝试建立主要和辅助通话用户,但是在收到以下错误后不确定如何格式化关系
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).
您必须为related_name两个ForeignKeys列定义不同的名称。例如:
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
另请参阅ForeignKey.related_name文档:
ForeignKey.related_name
用于从相关对象到此对象的关系的名称。它也是related_query_name(用于目标模型的反向过滤器名称的名称)的默认值。有关完整的解释和示例,请参见相关的对象文档。注意,在抽象模型上定义关系时必须设置此值。并且当您这样做时,可以使用一些特殊的语法。
related_query_name