python config_error ai_generated true

sqlalchemy.exc.ArgumentError: Mapper Mapper|User|users could not assemble any primary key columns for mapped table 'users'

ID: python/sqlalchemy-missing-primary-key

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2025-02-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Model class lacks a primary key column definition.

generic

中文

模型类缺少主键列定义。

Workarounds

  1. 95% success Add a primary key column.
    class User(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
  2. 90% success Use __mapper_args__ to specify primary key from existing columns.
    class User(Base):
        __tablename__ = 'users'
        email = Column(String, primary_key=True)  # if email is unique

Dead Ends

Common approaches that don't work:

  1. Adding a column without primary_key=True. 80% fail

    SQLAlchemy requires explicit primary key constraint.

  2. Using composite primary key with non-unique columns. 60% fail

    Must ensure uniqueness; otherwise mapping fails.