简体   繁体   English

带有 2 个 primary_keys 的 SQLAlchemy 表如何自动递增第一个主键

[英]SQLAlchemy table with 2 primary_keys how to autoincrement the first primary key

I have table with 2 primary keys, where second primary key is also a foreign key.我有 2 个主键的表,其中第二个主键也是一个外键。 When I try to populate the DB I will get "NOT NULL constraint failed: items.id1" error.当我尝试填充数据库时,我会收到“NOT NULL 约束失败:items.id1”错误。 When populating I will always provide known id for id2.填充时,我将始终为 id2 提供已知 ID。 So how can I make the sqlalchemy to autoincrement id1?那么如何让 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)

Combination of id1 and id2 has to always be unique, and combination of those 2 are used to identify the items. id1 和 id2 的组合必须始终是唯一的,并且这 2 的组合用于标识项目。 id1 isn't enough since databases can be in several locations and tables are synchronized time to time. id1 是不够的,因为数据库可以位于多个位置并且表不时同步。

I already tried this solution but it's outdated and doesn't work anymore: How to insert a row with autoincrement id in a multi-primary-key table?我已经尝试过这个解决方案,但它已经过时并且不再起作用: 如何在多主键表中插入具有自动增量 ID 的行?

EDIT: Work around for this problem is to use Postgres DB.编辑:解决此问题的方法是使用 Postgres DB。 SQLite is lite but dumb. SQLite 是轻量级但愚蠢的。

If you are using sqlite:如果您使用的是 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)

If you are using mysql, then simple autoincrement will work:如果您使用的是 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)

PS: Drop table first and try again. PS:先丢表再试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM