我在数据库中有两个模型,如
class Base(object):
def __tablename__(self):
return self.__name__.lower()
id = Column(Integer, primary_key=True, nullable=False)
utc_time = Column(BigInteger, default=utc_time, onupdate=utc_time)
class EntityModel(Base):
__tablename__ = 'entities'
town_id = Column(Integer, ForeignKey('towns.id', ondelete='CASCADE'), nullable=False)
type = Column(Integer, nullable=False)
level = Column(Integer, nullable=False, default=Level.LEVEL_ONE)
energy = Column(Float, nullable=False, default=0)
x = Column(Integer, nullable=False)
y = Column(Integer, nullable=False)
class CommandModel(Base):
__tablename__ = 'commands'
entity_id = Column(Integer, ForeignKey('entities.id', ondelete='CASCADE'), nullable=False)
command = Column(Integer, nullable=False)
started_at = Column(BigInteger, nullable=False)
ends_at = Column(BigInteger, nullable=False)
type = Column(Integer, default=None)
实体可以有一个或没有命令。如何获取对实体,命令(实体可以不带命令存在)
我试过但是它不起作用
for e, c in session.query(EntityModel, CommandModel).join(CommandModel).filter(EntityModel.town_id == 100).all():
答案 0 :(得分:2)
您可以使用outerjoin
进行左外连接,这似乎是您想要的。
http://docs.sqlalchemy.org/en/rel_0_7/orm/query.html#sqlalchemy.orm.query.Query.outerjoin