I want to know how to query data from multiple tables with multiple conditions.
My example db has the following tables:
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)
We have in this database a person with a specific location. My goal is to write a query where I can check conditions of the Location table and the Person table.
A person with the name Eric lives in Houston. Now I want to know if I already have an Eric from Houston in my database.
The following query doesn't work.
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")
The problem in my query is the last line where I check the location but I don't know how to solve it. Maybe someone has a working example with the SQLAlchemy method exists()?