英文:
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'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论