Mahi
Mahi

Reputation: 21903

Why does Flask-SQLAlchemy require a primary key?

If I define a table without a primary key:

class CustomAttribute(db.Model):
    player = db.Column(db.Integer, db.ForeignKey('player.id'))
    key = db.Column(db.Text, nullable=False)
    value = db.Column(db.Text, nullable=False)

I get an error:

sqlalchemy.exc.InvalidRequestError: Class <class 'rpgquest.models.CustomAttribute'> does not have a __table__ or __tablename__ specified and does not inherit from an existing table-mapped class.

The only workaround is to manually define __tablename__, but why is this required?

I don't need a primary key, since the only requests are to get all players with a key-value pair of X, or to get all key-value pairs for a certain player, and a player can not have duplicate keys.

Upvotes: 1

Views: 4644

Answers (1)

jwodder
jwodder

Reputation: 57470

Flask-SQLAlchemy requires a primary key because the SQLAlchemy ORM requires a primary key:

The SQLAlchemy ORM, in order to map to a particular table, needs there to be at least one column denoted as a primary key column ... Most ORMs require that objects have some kind of primary key defined because the object in memory must correspond to a uniquely identifiable row in the database table; at the very least, this allows the object can be targeted for UPDATE and DELETE statements which will affect only that object’s row and no other. However, the importance of the primary key goes far beyond that. In SQLAlchemy, all ORM-mapped objects are at all times linked uniquely within a Session to their specific database row using a pattern called the identity map, a pattern that’s central to the unit of work system employed by SQLAlchemy, and is also key to the most common (and not-so-common) patterns of ORM usage.

Upvotes: 5

Related Questions