python - SQLAlchemy 中的一对多关系

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

我在 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, "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/

相关文章:

python - 为什么我的 Flask 错误处理程序没有被调用?

python - 根据行号删除数据帧的行

python - 计算用于对象检测的混淆矩阵的正确方法是什么?

python - 无法在 python 列表中追加元素

python-3.x - 如何在 VS Code 终端中激活 python 虚拟环境?

python - 我需要找到用户输入数字列表的平均值,但有些东西不起作用

python - 试图找出为什么我的页面加载时间太慢

python - 权限错误 : [Errno 13] Permission denied in Ubuntu with flask

python - 从 Pandas 的日期列中查找特定日期的日期差异

android - 使用 SL4A (Python) 和蓝牙