2017-02-22 9 views
0

Если я определить таблицу без первичного ключа:Зачем нужна флэшка-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

Ahh, так что это похоже на словарь объектов, где первичный ключ является ключом dict? Это, наверное, немного сложнее, но с этой идеей? –

Смежные вопросы