多个字段对应一个外键时,会报错,如:
class Storehouse_list(models.Model):#库位列表
nid = models.AutoField(primary_key=True)
title = models.CharField(max_length=32)#仓库名称 class Storehouse_change(models.Model):#调库单
nid = models.AutoField(primary_key=True)
matter = models.ForeignKey(to='Matter_list',to_field='nid',on_delete=models.CASCADE)#物料名称
number = models.IntegerField#数量
storehouse_in = models.ForeignKey(verbose_name='出仓仓库',to='Storehouse_list',to_field='nid',on_delete=models.CASCADE)#物料所调入的仓库
storehouse_out = models.ForeignKey(verbose_name='入仓仓库',to='Storehouse_list',to_field='nid',on_delete=models.CASCADE)#物料调出的仓库
create_date = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
create_user = models.ForeignKey(to="UserInfo",to_field="nid",on_delete=models.CASCADE)#操作员
同时外键关联库位列表,会报错。
解决办法:给models.ForeignKey()加入related_name参数,定义不同的关联名称,如修改上面代码中的storehouse_in和storehouse_out即可解决问题:
storehouse_in = models.ForeignKey(verbose_name='出仓仓库',to='Storehouse_list',to_field='nid',related_name="出仓仓库",on_delete=models.CASCADE)#物料所调入的仓库
storehouse_out = models.ForeignKey(verbose_name='入仓仓库',to='Storehouse_list',to_field='nid',related_name="入仓仓库",on_delete=models.CASCADE)#物料调出的仓库