【发布时间】:2019-04-15 01:56:36
【问题描述】:
我想知道如何从多个表中查询多个条件的数据。
我的示例数据库有以下表格:
class Location(Base):
__tablename__ = "location"
id = Column('id', Integer, primary_key=True)
location = Column('Location', String)
class Person(Base):
__tablename__ = "person"
id = Column('id', Integer, primary_key=True)
name = Column('Name', String, unique=True)
profession = Column('Profession', String)
location_id = Column(Integer, ForeignKey('location.id'))
location = relationship(Location)
我们在这个数据库中有一个具有特定位置的人。我的目标是编写一个查询来检查Location 表和Person 表的条件。
一个名叫埃里克的人住在休斯顿。现在我想知道我的数据库中是否已经有来自休斯顿的 Eric。
以下查询无效。
new_location = Location(location='Houston')
obj = Person(name='Eric', profession='Teacher', location=new_location)
if session.query(Person).filter(Person.name == obj.name,
Person.profession == obj.profession,
Person.location_id == obj.location.id).first() == None:
session.add(obj)
session.commit()
print("Insert sucessful")
我的查询中的问题是我检查位置的最后一行,但我不知道如何解决它。也许有人有一个使用 SQLAlchemy 方法 exists() 的工作示例?
【问题讨论】:
标签: python python-3.x sqlalchemy filtering exists