【问题标题】:SQLAlchemy table with 2 primary_keys how to autoincrement the first primary key具有 2 个主键的 SQLAlchemy 表如何自动递增第一个主键
【发布时间】:2016-03-22 09:35:28
【问题描述】:

我有 2 个主键的表,其中第二个主键也是外键。当我尝试填充数据库时,我会收到“NOT NULL constraint failed: items.id1”错误。填充时,我将始终为 id2 提供已知 id。那么如何使 sqlalchemy 自动增加 id1?

class items(Base):
    __tablename__ = 'items'
    id1 = Column(BIGINT(unsigned=True).with_variant(Integer, "sqlite"), primary_key=True,)
    #location id
    id2 = Column(Integer, ForeignKey('table2.id'), primary_key=True)

id1 和 id2 的组合必须始终是唯一的,并且这 2 的组合用于识别项目。 id1 是不够的,因为数据库可以位于多个位置,并且表会不时同步。

我已经尝试过这个解决方案,但它已经过时并且不再有效:How to insert a row with autoincrement id in a multi-primary-key table?

编辑: 解决此问题的方法是使用 Postgres DB。 SQLite 很精简但很笨。

【问题讨论】:

  • 试试这个 autoincrement=True
  • 没什么,同样的错误。
  • 另一种选择是使用 uuids 而不是 2 个主键。这样您就始终知道您的 id 是唯一的:from uuid import uuid4; id = Column(String, primary_key=True, default=lambda: uuid4())。此时,您可以将主键放在外键上,因为它不再需要作为标识符。

标签: python sqlalchemy


【解决方案1】:

如果你使用的是 sqlite:

id1 = Column(BIGINT(unsigned=True).with_variant(Integer, "sqlite"), primary_key=True, sqlite_autoincrement=True)
id2 = Column(Integer, ForeignKey('table2.id'), primary_key=True, sqlite_autoincrement=False)

如果您使用的是 mysql,那么简单的自动增量将起作用:

id1 = Column(BIGINT(unsigned=True).with_variant(Integer, "sqlite"), primary_key=True, autoincrement=True)
id2 = Column(Integer, ForeignKey('table2.id'), primary_key=True, autoincrement=False)

P.S.:先删除表再试一次。

【讨论】:

  • “传递给列的未知参数:['sqlite_autoincrement']”并且当 id2 的 autoincrement = False 时,它​​仍然显示“NOT NULL 约束失败”。目前我的数据库是 sqlite3,但我很快会将其更改为 postgres,也许它会在那里工作......
  • 使用 sqlalchemy 1.1.3,在 SQLite 上,我必须使用 Column(BIGINT().with_varient(Integer, "SQLite"), primary_key=True)。 SQLite_autoincrement 无法识别,但对于主键应该是自动的。 docs.sqlalchemy.org/en/latest/dialects/…
猜你喜欢
  • 2014-10-11
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-12
  • 2015-05-11
  • 1970-01-01
相关资源
最近更新 更多