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

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

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

问题

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

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

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?

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

答案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/

因此,实际上您会有:

  1. class Object(models.Model):
  2. unmanaged_fk = models.ForeignKey('UnmanagedObject', blank=True, null=True, on_delete=models.SET_NULL)
  3. class UnmanagedObject(models.Model):
  4. some_field = models.CharField(max_length=200)
  5. ...
  6. class Meta:
  7. managed=False
  8. 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:

  1. class Object(models.Model):
  2. unmanaged_fk = models.ForeignKey('UnmanagedObject', blank=True, null=True, on_delete=models.SET_NULL)
  3. class UnmanagedObject(models.Model):
  4. some_field = models.CharField(max_length=200)
  5. ...
  6. ...
  7. class Meta:
  8. managed=False
  9. 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:

确定