【问题标题】:sqlalchemy fails to execute session.add() in a for loop [duplicate]sqlalchemy 无法在 for 循环中执行 session.add() [重复]
【发布时间】:2021-11-16 07:14:56
【问题描述】:

我在for 循环中遇到了session.add(record) 的问题。下面是一个调用来解析列表和添加记录的函数示例:

def insert_lists(list, table, default_value=''):
    for x in list:
        record = table.query.filter_by(name=x).first()
        if record is None:
            record = table(name=x)
            if default_value != '':
                record.default_new = (x == default_value)
            db.session.add(record)
            db.session.flush()
        db.session.commit()

这是通过在模块内调用@staticmethod 函数来启动的,例如:

class Some_table(db.Model):
    __tablename__ = 'some_tables'
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4())
    name = Column(String(), unique=True, nullable=False, ...)
    default_new = Column(Boolean, nullable=False)
    
    @staticmethod
    def insert_data_in_some_table():
        from app.functions import insert_lists #(list, table, default_value)
        types = [
            'Generic', 'Specific', 'Unique', 'Unicorn', 'Other'
        ]
        insert_lists(types, Some_table, 'Generic')

这些用于使用大量预先打包的数据填充数据库。它没有恢复到session.flush()。无论session.commit() 是在insert_lists() 函数内还是在@staticmethod 代码的末尾,它也都有效。它工作正常,然后停止了。显然,我不知道是什么触发了这种变化。现在,它只选择列表中的第一个元素,将其添加到数据库中,并引发werkzeug.exceptions.Conflict: 409 Conflict: duplicate key value violates unique constraint "pk_some_tables" DETAIL: Key (id)=(2a1c72c6-871e-46a8-ba75-119649c9e083) already exists.

任何关于在哪里寻找问题的建议将不胜感激。

【问题讨论】:

  • 我不能说它以前为什么有效 - 一定是在代码、数据或两者中有所不同。
  • 谢谢。一切都好,结局好。

标签: postgresql for-loop flask-sqlalchemy commit werkzeug


【解决方案1】:

您的问题在于您声明主键的模型,SQLAlchemy 会自动执行默认情况下的任何参数,包括函数,只需更改:

uuid.uuid4()

通过

uuid.uuid4

官方文档如下,在最后一个例子中:

Python-Executed Functions

【讨论】:

  • 请不要回答明显的重复。
  • @snakecharmerb - 你介意猜测一下这个模型以前是如何工作的吗?它使用 uuid.uuid4() 在嵌套循环中填充了数千行。您的解决方案很有效,但我很好奇为什么会出现这种不一致。
猜你喜欢
  • 1970-01-01
  • 2015-12-06
  • 2021-02-13
  • 2012-07-22
  • 2019-05-28
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多