将数据添加到SQLAlchemy中的继承类

时间:2017-03-24 16:15:06

标签: python sqlalchemy

我正在尝试创建一个数据库来存储人员和地址:家庭和工作。我使用了继承的类来创建两个地址。

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import ForeignKey, Column, Integer, String, Float
from sqlalchemy.orm import relationship

Base = declarative_base()

class Colleague(Base):
""" Generic Colleague """
    __tablename__ = 'colleagues'
    id = Column(Integer, primary_key=True)
    first_name = Column(String(50))
    last_name = Column(String(50))
    home_address = relationship('Home_Address', back_populates='colleague')
    work_address = relationship('Work_Address', back_populates='colleague')

class Address(Base):
    """ Generic Address """
    __tablename__ = 'addresses'
    id = Column(Integer, primary_key=True)
    adr_type = Column('type', String(50))
    country = Column(String(50))
    state = Column(String(50))
    county = Column(String(50))
    city = Column(String(50))
    district = Column(String(50))
    street = Column(String(50))
    house_number = Column(Integer)
    postal_code = Column(String(50))

    __mapper_args__ = {
        'polymorphic_on' : adr_type
    }

    class Home_Address(Address):
    __tablename__ = 'home_addresses'
    id = Column(Integer, ForeignKey('addresses.id'), primary_key=True)
    colleague_id = Column(Integer, ForeignKey('colleagues.id'))
    colleague = relationship('Colleague', back_populates='home_address')
    __mapper_args__ = {
        'polymorphic_identity' : 'home_addresses'
    }

class Work_Address(Address):
    __tablename__ = 'work_addresses'
    id = Column(Integer, ForeignKey('addresses.id'), primary_key=True)
    colleague_id = Column(Integer, ForeignKey('colleagues.id'))
    colleague = relationship('Colleague', back_populates='work_address')
    __mapper_args__ = {
        'polymorphic_identity' : 'work_addresses'
    }

然后我尝试向同事添加地址

adr1 = Home_Address(country='France', city='Paris')
adr2 = Work_Address(country='France', city='Lyon')
col = Colleague(first_name='Joe', last_name='Dalton')
col.home_address = adr1
col.work_address = adr2

但是会发生这种情况:

TypeError: Incompatible collection type: Home_Address is not list-like

col.home_address给出一个空列表,而不是给我对象Home_Address,我该如何设置它? 或者可能有更简单的方法吗?

1 个答案:

答案 0 :(得分:1)

同事 - >地址是一对多的关系,对吧?那会是一个列表,所以也许尝试这样的事情:

adr1 = Home_Address(country='France', city='Paris')
adr2 = Work_Address(country='France', city='Lyon')
col = Colleague(first_name='Joe', last_name='Dalton')
col.home_address = [adr1]
col.work_address = [adr2]