亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將記錄從一張表轉移到另一張表?

如何將記錄從一張表轉移到另一張表?

回首憶惘然 2023-05-09 10:42:05
我有以下示例表:class DestDB(Base):    __tablename__ = "dest_db"    __table_args__ = (Index('nameplace', "name", "place"))    id = Column(Integer, primary_key=True)    name = Column(String(100))    place = Column(String(100))我很習慣使用字典來添加記錄。例如:dict = {"name": "foo", "place": "bar"}session.add(DestDB(**dict))但是,如何將記錄從一張表轉移到另一張表?我想我可以查詢源表,遍歷每條記錄,將其轉換成字典,然后添加上面的結果。但是,我確定必須有一個更簡潔的解決方案?源數據庫中會有重復的name和place記錄組合,所以我不想使用任何類型的批量操作,除非它不會插入任何重復記錄。假設源數據庫如下所示:class SourceDB(Base):    __tablename__ = "source_db"    id = Column(Integer, primary_key=True)    name = Column(String(100))    place = Column(String(100))我只想傳輸name和place字段。
查看完整描述

1 回答

?
智慧大石

TA貢獻1946條經驗 獲得超3個贊

我建議堅持使用The Zen of Python。


顯式優于隱式。


我會在 ? 上實現一個方法SourceDB來提供我想要的對象的字典格式。


class SourceDB(Base):

    __tablename__ = "source_db"


    id = Column(Integer, primary_key=True)

    name = Column(String(100))

    place = Column(String(100))


    def as_dict(self):

        return dict(name=self.name, place=self.place)

并像這樣使用它


session.add(DestDB(**src_obj.as_dict()))

盡管您可以更動態地執行此操作,但我仍然建議使用更明確的方法。


class SourceDB(Base):

    __tablename__ = "source_db"


    id = Column(Integer, primary_key=True)

    name = Column(String(100))

    place = Column(String(100))


    def as_dict(self, fields):

        return dict(field: getattr(self, field) for field in fields if hasattr(self, field))

并這樣做


session.add(DestDB(src_obj.as_dict(("name", "place"))))


查看完整回答
反對 回復 2023-05-09
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號