【问题标题】:SQLAlchemy: insert record if certain record and relationship data does not already existSQLAlchemy:如果某些记录和关系数据不存在,则插入记录
【发布时间】: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


    【解决方案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() 来完成同样的事情,但我认为上面的内容更简单一些。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-04
    • 2013-11-15
    • 1970-01-01
    • 2021-09-03
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多