SQLAlchemy类有一个类变量而不是实例变量?

时间:2017-11-26 07:56:24

标签: python python-3.x sqlalchemy

我写了一些域类,如:

class Klient(Base):
    __tablename__ = 'klient'
    __table_args__ = (
        Index('pg_klient_index', 'nums', 'sals', 'k_id'),
    )
    def __init__(self):
        self.dogovors=list()
    adrrab = Column(String(200))
    c1uid = Column(String(45))
    cods = Column(String(10))
    d_first = Column(Date)
    d_vidan = Column(Date)
    docum = Column(String(40))
    doljn = Column(String(160))
    id = Column(BigInteger, primary_key=True, server_default=text("nextval('klient_id_seq'::regclass)"))
    inn = Column(String(15))
    izm = Column(Date)
    k_id = Column(BigInteger, nullable=False)
    .....
    vidan = Column(String(300))
    xmldat = Column(Date)
    xmlnum = Column(String(15))
    zak = Column(Numeric(1, 0))
    dogovors = []

我用代码选择所有记录:

klients = ss.query(Klient).all()
for k in klients:
    q = ss.query(Dogovor).filter(Dogovor.sals == k.sals, Dogovor.kl_id == k.k_id).all()
    if len(q):
        k.dogovors.extend(q)

我看到了意想不到的行为:

enter image description here

enter image description here

enter image description here

每个对象都有相同的 dogovors 实例吗?

UPD:

我试着写:

class Klient(Base):
    __tablename__ = 'klient'
    __table_args__ = (
        Index('pg_klient_index', 'nums', 'sals', 'k_id'),
    )
    def __init__(self):
        self.dogovors=list()
    adrrab = Column(String(200))
    c1uid = Column(String(45))

但我有错误AttributeError: 'Klient' object has no attribute 'dogovors'

1 个答案:

答案 0 :(得分:0)

Some docs about that 如果SQLAlchemy创建了类的实例,则它不执行 init 方法。如果您需要执行某些方法,则需要使用@orm.reconstructor

进行标记

之后一切正常:

enter image description here

enter image description here