Is it possible to specify a foreign key for a table field in Django models.py to any table from the database?

huangapple go评论70阅读模式
英文:

Is it possible to specify a foreign key for a table field in Django models.py to any table from the database?

问题

可以将数据库中的表"table"作为外键指定吗?

class Object(models.Model):
    object_id = models.IntegerField(unique=True)
    param = models.ForeignKey('table', on_delete=models.DO_NOTHING)
...
英文:

Suppose there is a table in the database "table", not created by Django. Is it possible to specify it as a foreign key in any way?

class Object(models.Model):
    object_id = models.IntegerField(unique=True)
    param = models.ForeignKey('table', on_delete= models.DO_NOTHING)
...

答案1

得分: 1

有关Django模型的元选项,用于指定表存在但不由Django管理的信息:

https://docs.djangoproject.com/en/4.2/ref/models/options/#managed

Django还可以通过inspectdb管理命令来指向表格以构建模型类:

https://docs.djangoproject.com/en/4.2/howto/legacy-databases/

因此,实际上您会有:

class Object(models.Model):
    unmanaged_fk = models.ForeignKey('UnmanagedObject', blank=True, null=True, on_delete=models.SET_NULL)

class UnmanagedObject(models.Model):
    some_field = models.CharField(max_length=200)
    ...

    class Meta:
        managed=False
        db_table = 'Name_Of_My_Database_Table'
英文:

There is a meta option on Django models to specify that the table exists but is not managed by Django:

https://docs.djangoproject.com/en/4.2/ref/models/options/#managed

Django can also build the model classes by pointing to the tables using the inspectdb manage command:

https://docs.djangoproject.com/en/4.2/howto/legacy-databases/

So effectively you'd have:

class Object(models.Model):
    unmanaged_fk = models.ForeignKey('UnmanagedObject', blank=True, null=True, on_delete=models.SET_NULL)

class UnmanagedObject(models.Model):
    some_field = models.CharField(max_length=200)
    ...
    ...

    class Meta:
        managed=False
        db_table = 'Name_Of_My_Database_Table'

huangapple
  • 本文由 发表于 2023年6月1日 04:13:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定