SQLAlchemy:如果某些记录和关系数据尚不存在,则插入记录

时间:2018-11-12 10:51:13

标签: python python-3.x sqlalchemy filtering exists

我想知道如何从具有多个条件的多个表中查询数据。

我的示例数据库具有以下表格:

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)的人住在休斯敦。现在,我想知道我的数据库中是否已经有来自休斯顿的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()有一个可行的示例?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作来加入PersonLocation并过滤名称和位置与您创建的新人物实例相同的任何记录。该查询将返回记录或None,因此您可以在if中使用结果(请记住,缩进很重要-可能是您问题中的代码示例未正确复制)。

new_location = Location(location='Houston')
new_person = Person(name='Eric', profession='Teacher', location=new_location)

person_location_exists = session.query(Person).\
    join(Location).\
    filter(Person.name == new_person.name).\
    filter(Location.location == new_location.location).\
    first()

if not person_location_exists:
    session.add(new_person)
    session.commit()
    print("Insert successful")

您可以使用exists()完成相同的操作,但是我认为上面的操作要简单一些。