如何使用父表的值填充 Django 模型/表之一中的外键列?

我有一个 Django 模型/SQL 表,它是静态的,并且总是有 4 行,其中一列(ID)作为主键,如下所示


Status_ID  Status 

1          active

2          inactive

3          pending

4          deprecated

我有另一个 Django 模型,其中记录将每天插入并具有上表的外键 (Status_ID),并且必须始终插入 status_ID 为 2。


ID My_code     status_ID Location

1   some code  2         India

2   other code 2         USA

我有以下代码填充第二个表


T1= Table2(My_code='some code', Location='India')

T1.save()

用 2, always 填充第二个表的 status_ID 列的那一行应该是什么?


模型定义如下:-


class Table1(models.Model):

    Status_ID=models.AutoField(primary_key=True)

    Status=models.CharField(max_length=45, blank=True, null=True)


    class Meta:

        managed = True

        db_table = 'Table1'



Class Table2(models.Model):

    ID=models.AutoField(primary_key=True)

    My_code=models.CharField(max_length=45, blank=True, null=True)

    status_ID=models.ForeignKey('Table1', models.DO_NOTHING, blank=True, null=True)

    Location=models.CharField(max_length=45, blank=True, null=True)


    class Meta:

        managed = True

        db_table = 'Table2'


慕哥6287543
浏览 108回答 1
1回答

MYYA

你可以这样做:status = Table1.objects.get(Status="active")T1= Table2(My_code='some code', Location='India', status_ID=status)T1.save()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python