社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

如何用父表的值填充其中一个django模型/表中的外键列?

Abhilash Kumar • 7 年前 • 1842 次点击  

我有一个django model/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填充第二个表的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'
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38724
文章 [ 1 ]  |  最新文章 7 年前
Cyrlop
Reply   •   1 楼
Cyrlop    8 年前

您可以这样做:

status = Table1.objects.get(Status="active")
T1= Table2(My_code='some code', Location='India', status_ID=status)
T1.save()