【问题标题】:django two column foreign key reference to one columndjango 两列外键引用一列
【发布时间】:2022-01-03 21:56:02
【问题描述】:

class Personal(models.Model):
    Personal_ID = models.SmallIntegerField(primary_key=True)
    Name = models.CharField(max_length=20)
    
    class Meta:
        managed = True
        db_table = 'Personal'

class Tests(models.Model):
    
    Requestor = models.ForeignKey('Personal',models.DO_NOTHING,
    db_column='Personal_ID')
    Analyst = models.ForeignKey('Personal', on_delete=models.CASCADE,db_column='Personal_ID',related_name='+')
   
    class Meta:
        managed = True
        db_table = 'Tests'

I have this problem, I have two columns foreigner key and reference one columns, which works in mysql, but it did not work in Django models. it showed there are two same db_columns in one models and it is not allowed, how to fix it. I will appreciate it

here is the code. how to avoid to use one db_column twice?

【问题讨论】:

标签: django model


【解决方案1】:

db_column = 用于此字段的数据库列的名称。如果没有给出,Django 将使用该字段的名称。

要么从它们中删除 db_column,要么将它们设置为不同的值。

【讨论】:

  • 谢谢。我明白了。我发现引用被自动分配给父表的主键。而我的db_column是数据库表的列。谢谢。
【解决方案2】:

文档说: “用于该字段的数据库列的名称。如果没有给出,Django 将使用该字段的名称。”

您的模型在两个字段上有 db_column=Personal_ID。这意味着您要命名两个字段Personal_ID。不应有重复的列名;每列必须有一个唯一的名称。

解决方案是从其中一个字段中删除 db_column=Personal_ID,然后另一个字段可以有 db_column=Another_Personal_ID

https://docs.djangoproject.com/en/4.0/ref/models/fields/

【讨论】:

  • 非常感谢您的帮助。是的,我阅读了文档并发现我错误地使用了 db_column。我需要使用数据库表的列名,而不是父表。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 2011-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多