【问题标题】:One to many relationship in SQLAlchemySQLAlchemy中的一对多关系
【发布时间】:2019-12-06 10:06:30
【问题描述】:

我在 SQLAlchemy 中有以下一对多的关系。

class Application(Base):
    __tablename__  = "application"

    id = Column("id", Integer, primary_key = True, autoincrement = True)        
    organization_id = Column(Integer, ForeignKey('organization.id'))
    organization = relationship("Organization", uselist=False, back_populates="applications")

class Organization(Base):
    __tablename__  = "organization"

    id = Column("id", Integer, primary_key = True, autoincrement = True)
    name = Column("name", String(128), unique = True, nullable = False)
    applications = relationship("Application", back_populates="organization")

简单地说,“一个组织可以有多个应用程序,一个应用程序可以有一个组织”。

我推断的方式是Organization 类是父类,Application 类是子类。

我有一个包含 应用程序 列表的 .csv 文件。我正在解析列表以从每一行创建ApplicationOrganization 的实例。然后我设置application.organization = organization,然后设置session.add(application)

当我将应用程序添加到数据库时,如果依次添加的组织是第一次添加的,则它已正确插入。但是,当发现一个应用程序与插入的应用程序具有相同的组织时,它会抱怨错误 -

sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1062, "键 'name' 的重复条目 'MICROSOFT'")

我了解这是因为该组织已存在于数据库中。

SQLAlchemy 不会处理这种情况吗?如果没有,我该如何处理?

【问题讨论】:

    标签: python python-3.x flask sqlalchemy flask-sqlalchemy


    【解决方案1】:

    您可能每次都在创建一个新组织,而不是获取已经存在的组织(如果存在的话)。

    这段代码应该为您指明正确的方向

    # Organization name from your CSV
    org_name = 'MICROSOFT'
    
    # Get Organization if it already exists
    application.organization = Organization.query.filter(Organization.name == org_name ).first()
    
    # If the Organization doesn't exist, create a new one
    if application.organization is None:
        application.organization = Organization(name=org_name)
    

    【讨论】:

    • 所以 SQLAlchemy 不会自动处理这个问题?
    • @KunalShah - “这个”到底是什么?您已经告诉它不允许组织具有相同的名称,然后您尝试使两个组织具有相同的名称。它会引发错误,因为您已明确要求它在这种情况下这样做 (unique = True)。
    • 如果不存在,SQLAlchemy 不会做相当于创建的操作吗?
    • 不是内置的,但您可以创建一个。请参阅this 问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2021-08-31
    • 2020-11-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 2012-06-14
    相关资源
    最近更新 更多