我在 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 文件,其中包含应用程序列表。我正在解析列表以从每一行创建 Application
和 Organization
的实例。然后我设置application.organization =organization
,然后执行session.add(application)
。
当我应用到数据库时,如果依次添加的组织是第一次添加,则插入正确。但是,当发现一个应用程序与在提示错误之前插入的组织具有相同的组织时 -
sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1062, "Duplicate entry 'MICROSOFT' for key 'name'")
据我了解,这是因为该组织已存在于数据库中。
SQLAlchemy 不会处理这种情况吗?如果没有,我该如何处理?
最佳答案
您可能每次都会创建一个新组织,而不是获取已经存在的组织(如果存在)。
这段代码应该为您指明正确的方向
# 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)
关于python - SQLAlchemy 中的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57247526/