如何解决Django | 2外键对自己的模型显示错误只需一把外键就可以了
在名为Station的model.py中,我有2个带有fireignkey的索引指向相同的models.py(station)。如果我只使用一个索引与此关系,这行得通。但是,如果我具有与相同models.py(Station)的第二个索引关系,则会出现错误消息:
错误:
station.Station.comunication_point: (fields.E304) Reverse accessor for 'Station.comunication_point' clashes with reverse accessor for 'Station.origin_watertank'.
HINT: Add or change a related_name argument to the definition for 'Station.comunication_point' or 'Station.origin_watertank'.
station.Station.origin_watertank: (fields.E304) Reverse accessor for 'Station.origin_watertank' clashes with reverse accessor for 'Station.comunication_point'.
HINT: Add or change a related_name argument to the definition for 'Station.origin_watertank' or 'Station.comunication_point'.
System check identified 2 issues (0 silenced).
如何对自己的模型进行2次外键操作而不会出现错误?谢谢!
2个带外键的Station模型的索引。py
origin_watertank = models.ForeignKey ('self',null=True,on_delete=models.CASCADE,blank=True)
comunication_point = models.ForeignKey ('self',blank=True)
文件 models.py:
class Station(models.Model):
timestamp_station = models.DateTimeField ('Fecha edición',blank=True)
code_station = models.CharField('Código',max_length=50,blank=True)
name_station = models.CharField('Nombre',blank=True)
origin_watertank = models.ForeignKey ('self',blank=True)
comunication_point = models.ForeignKey ('self',blank=True)
objects = StationManager()
class Meta:
verbose_name = 'Station'
verbose_name_plural = 'Stations'
def __str__(self):
#return [self.name,self.area,self.codigo]
return str(self.id) + '-' + str(self.name_station)
解决方法
您需要按照错误中的说明添加related_name
:
origin_watertank = models.ForeignKey ('self',null=True,on_delete=models.CASCADE,blank=True,related_name="origins")
comunication_point = models.ForeignKey ('self',related_name="comunications")
您有两个指向同一个源的外键,以便能够进行反向查找,您需要为每个外键提供一个related_name
,以便Django可以将它们分开。
这将允许您进行这种查找:
station = Station.objects.get(pk=1)
# will return all the stations based on comunication_point
stations.comunications.all()
# will return all the stations based on origin_watertank
stations.origins.all()
随时可以更改名称。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。