SQLAlchemy:关于孩子的一对一关系字段

时间:2016-07-19 16:55:08

标签: python sqlalchemy

所以基本上我有一对多的关系,我想在一个属性上订购“多个”,这是另一个一对一的关系。

......或举例:

enter image description here

在这里,我想按日期订购

我看过SQLAlchemy: How to order query results (order_by) on a relationship's field?,为query解释了它,但是我想在relationship上使用它,如果目标列只支持order_by直接存在于 Things 上。

编辑:这似乎现在有效(我的问题仍然存在):

from sqlalchemy import Column, Integer, DateTime, ForeignKey 
from sqlalchemy import column, text, select, create_engine
from sqlalchemy.orm import relationship, column_property, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Catalog(Base):
    __tablename__ = 'catalogs'
    id = Column(Integer, primary_key=True)
    things = relationship('Thing', order_by='Thing.date')

class Thing(Base):
    __tablename__ = 'things'
    id = Column(Integer, primary_key=True)
    catalog_id = Column(Integer, ForeignKey('catalogs.id'))
    catalog = relationship('Catalog')
    info = relationship('Info', uselist=False)
    date = column_property(select([column('date')], from_obj='infos').\
        where(text('thing_id == things.id')))

class Info(Base):
    __tablename__ = 'infos'
    id = Column(Integer, primary_key=True)
    date = Column(DateTime)
    thing_id = Column(Integer, ForeignKey('things.id'))
    thing = relationship('Thing')

engine = create_engine('sqlite://', echo=True)
Base.metadata.create_all(engine, checkfirst=True)
session = sessionmaker(bind=engine)

session = session()
query = session.query(Catalog)

session.add(Catalog())
catalogs = query.all()
print('catalogs: {}'.format(catalogs))
print(catalogs[0].things)

请注意:

  • 我必须在from_obj='infos'中指定column_property,否则SQLAlchemy不会在SQL语句中添加FROM子句,因此找不到日期列。
  • 似乎需要
  • order_by='Thing.date'而不仅仅是order_by='date',即使该属性被命名为'date'。

我的问题:这种方法是否应该超出预期的方式,还是有另一种方法可以做到这一点?这看起来非常复杂。

0 个答案:

没有答案