第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

SQLAlchemy:單表繼承,子級中的同一列

SQLAlchemy:單表繼承,子級中的同一列

慕桂英546537 2021-03-28 14:38:23
我目前使用單表繼承策略映射類層次結構(我無法使用joind)。該層次結構可能如下所示:class Parent(Base):    __tablename__ = 'mytable'    __mapper_args__ = {        'polymorphic_on' : type,        'polymorphic_identity' : 'parent'    }    id = Column(Integer, primary_key = True)    type = Column(String(32), nullable = False)class Child1(Parent):    __mapper_args__ = { 'polymorphic_identity' : 'child1' }    property1 = Column(Integer)class Child2(Parent):    __mapper_args__ = { 'polymorphic_identity' : 'child2' }    property1 = Column(Integer)class Child3(Parent):    __mapper_args__ = { 'polymorphic_identity' : 'child3' }    other_property = Column(Integer)那么問題是,我想有一property1兩個Child1和Child2,但不是Child3。上面的當前代碼導致錯誤:sqlalchemy.exc.ArgumentError: Column 'property1' on class <class'__main__.Child2'>  conflicts with existing column 'mytable.property1'我當然可以添加其他層的繼承層次這Child1與Child2從派生,并包含property1列,但Child1和Child2幾乎不相互關聯(lián)的,但我想重用這兩個類相同的數(shù)據(jù)庫列。我已經(jīng)嘗試添加property1 = Child1.property1到,Child2但沒有成功(實例值未存儲在的數(shù)據(jù)庫中Child2)誰能指出如何重用另一個子類已定義的列?
查看完整描述

2 回答

?
繁星點點滴滴

TA貢獻1803條經(jīng)驗 獲得超3個贊

直接根據(jù)解決列沖突中的文檔進行改編:


from sqlalchemy import *

from sqlalchemy.orm import *

from sqlalchemy.ext.declarative import declarative_base, declared_attr


Base = declarative_base()


class Parent(Base):

    __tablename__ = 'mytable'


    id = Column(Integer, primary_key = True)

    type = Column(String(32), nullable = False)

    __mapper_args__ = {

        'polymorphic_on' : type,

        'polymorphic_identity' : 'parent'

    }


class Child1(Parent):

    __mapper_args__ = { 'polymorphic_identity' : 'child1' }


    @declared_attr

    def property1(cls):

        return Parent.__table__.c.get('property1', Column(Integer))


class Child2(Parent):

    __mapper_args__ = { 'polymorphic_identity' : 'child2' }


    @declared_attr

    def property1(cls):

        return Parent.__table__.c.get('property1', Column(Integer))


class Child3(Parent):

    __mapper_args__ = { 'polymorphic_identity' : 'child3' }


    other_property = Column(Integer)


e = create_engine("sqlite://", echo=True)

Base.metadata.create_all(e)


s = Session(e)

s.add_all([Child1(property1=1), Child2(property1=2), Child3(other_property=3)])

s.commit()


for p in s.query(Parent):

    if isinstance(p, (Child1, Child2)):

        print p.property1

    elif isinstance(p, Child3):

        print p.other_property


查看完整回答
反對 回復 2021-04-01
  • 2 回答
  • 0 關注
  • 252 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號