2017-02-22 1 views
0

Wenn ich eine Tabelle ohne Primärschlüssel definieren:Warum benötigt Flask-SQLAlchemy einen Primärschlüssel?

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) 

ich einen Fehler:

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. 

Die einzige Lösung ist manuell __tablename__, zu definieren, aber warum ist dies erforderlich?

Ich brauche keinen Primärschlüssel, da die einzigen Anforderungen sind, alle Spieler mit einem Schlüssel-Wert-Paar von X zu bekommen, oder alle Schlüssel-Wert-Paare für einen bestimmten Spieler zu bekommen, und ein Spieler kann nicht haben doppelte Schlüssel

+1

Sie einen guten Primärschlüssel Kandidaten haben: '(Spieler, Schlüssel)'. –

+0

Ooooh ... Du machst mich wieder blöd: D @ IljaEverilä –

Antwort

2

Flask-SQLAlchemy benötigt einen Primärschlüssel, weil 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, es ist wie mit einem Wörterbuch der Objekte, wo der Primärschlüssel der Schlüssel des Diktats ist? Es ist wahrscheinlich ein bisschen komplexer, aber mit dieser Idee? –

Verwandte Themen