为什么Flask炼金术需要主键?

2024-10-03 15:21:28 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我定义一个没有主键的表:

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)

我得到一个错误:

^{pr2}$

唯一的解决方法是手动定义__tablename__,但是为什么需要这样做呢?在

我不需要主键,因为唯一的请求是获取所有具有X键值对的玩家,或者获取某个玩家的所有键值对,并且玩家不能有重复的密钥。在


Tags: textfalsedbmodel定义玩家columninteger
1条回答
网友
1楼 · 发布于 2024-10-03 15:21:28

Flask SQLAlchemy需要主键,因为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.

相关问题 更多 >