sqlalchemy在具有关系的表之间向上插入

2024-05-07 16:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

问题?

如果new和update存在于同一postgres数据库中具有关系的表之间,使用sqlalchemy插入if new和update的最优雅方式是什么?

上下文
用户查看阶段表;可以接受更改,然后在审阅后发送到生产表。

可能只是编辑了舞台或舞台上的新记录。

我从其他问题中找到了如何做到这一点,但所有问题都涉及到创建一个新对象和指定列名,例如

 rutable.ru=rustage.ru
 ...ect....

我的模型

^{pr2}$

伪代码

#check to see if records exists
if db.session.query(exists().where(models.rutable.id == rurow)).scalar():
    rustage=models.rustage.query.filter_by(id=rurow).first()
    ruprod=models.rutable.query.filter_by(id=rurow).first()
    form = rutable(obj=rustage)
    # import pdb;pdb.set_trace()
    form.populate_obj(ruprod)
else:
    rustage=models.rustage.query.filter_by(id=rurow).first()
    #how do i insert rustage into rutable and reset primary key?
    #without creating a new obj in which i have to specify each column name?
    #e.g. rutable(a=rustage.a,.....  1 million column names (i could use a form?

db.session.commit()

更新

我决定用表格
这是我想到的

rustage=models.rustage.query.filter_by(id=rurow).first()
if db.session.query(exists().where(models.rutable.id == rurow)).scalar():
    ruprod=models.rutable.query.filter_by(id=rurow).first()
    form = rutable(obj=rustage)
    form.populate_obj(ruprod)
else:
    ruprod=rutable(ru=rustage.ru)
    form = rutable(obj=rustage)
    form.populate_obj(ruprod)
rustage.reviewEdit=False
ruprod.reviewEdit=False
db.session.commit()

Tags: formidobjdbbyifmodelsru