2017-02-22 150 views
0

如果我定义一个表没有主键:为什么Flask-SQLAlchemy需要主键?

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) 

我得到一个错误:

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. 

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

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

+1

你有一个很好的主键候选:'(播放器,键)'。 –

+0

Ooooh ...你让我再次感到愚蠢:D @IljaEverilä –

回答

2

瓶-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.

+0

啊,这就像有一个主键是字典键的对象字典?这可能会更复杂一点,但有了这个想法? –