如何将外键设置为其他模型的字段?

编程入门 行业动态 更新时间:2024-10-25 09:31:15
本文介绍了如何将外键设置为其他模型的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想为另一个模型的字段设置外键.

I want to set a foreign key to a field of another model.

我尝试了外键to_field ='field_name'

I have tried Foreign Key to_field='field_name'

class Banks(models.Model): name = models.TextField() id = models.IntegerField(unique=True) class Meta: db_table = 'banks' class Branches(models.Model): ifsc = models.CharField(max_length=20, null=False) bank_id = models.ForeignKey(Banks, to_field='id', on_delete=models.CASCADE) branch = models.CharField(max_length=50)``` ProgrammingError: column branches.id does not exist LINE 1: SELECT "branches"."id", "branches"."ifsc", "branches"."bank_...

推荐答案

此问题不是由外键引起的.该错误发生在Branches模型中,该模型大概也具有 db_table Meta属性,并且基于旧表.

This problem is not caused by the foreign key. The error is happening in the Branches model, which presumably also has a db_table Meta attribute and is based on a legacy table.

您必须定义模型的主键.如果您不这样做,则Django会自动这样做,并将其命名为 id .对于您的Banks模型,应将 id 字段设置为 primary_key = True -或实际上将其完全删除,因为这是默认设置.您还需要为分支机构找到合适的pk,并在字段中进行声明.

You must define a primary key for your models. If you don't, Django will do so automatically and call it id. In the case of your Banks model, you should set that id field as primary_key=True - or indeed remove it completely, since that is the default. You need to find a suitable pk for Branches as well and declare it in the field.

对于您的实际问题,您无需执行任何操作;Django会自动将FK设置为​​指向目标模型的PK.

For your actual question, you don't need to do anything; Django will automatically set the FK to point to the PK of the target model.

class Bank(models.Model): # removed `id` as that is the default PK name = models.TextField() class Meta: db_table = 'banks' class Branch(models.Model): ifsc = models.CharField(max_length=20, primary_key=True) # assume this is the PK bank = models.ForeignKey(Bank, on_delete=models.CASCADE) branch = models.CharField(max_length=50) class Meta: db_table = 'branches'

还请注意,由于这些是旧表,您可能要向两个Meta类添加 managed = False .正如AKX所建议的那样,将模型名称设为单数是Django风格.您可以在不影响表名的情况下执行此操作,因为该表名已明确声明.

Note also, since these are legacy tables you probably want to add managed = False to both Meta classes. And as suggested by AKX, it is Django style to make model names singular; you can do that without affecting the table name since that is declared explicitly.

更多推荐

如何将外键设置为其他模型的字段?

本文发布于:2023-11-25 13:47:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630001.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   设置为   如何将   模型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!