Ich habe zwei Tabellen, tablet
und correspondent
:KeyError beim Hinzufügen von Objekten zu SQLAlchemy Assoziationsobjekt
class Correspondent(db.Model, GlyphMixin):
# PK column and tablename etc. come from the mixin
name = db.Column(db.String(100), nullable=False, unique=True)
# association proxy
tablets = association_proxy('correspondent_tablets', 'tablet')
def __init__(self, name, tablets=None):
self.name = name
if tablets:
self.tablets = tablets
class Tablet(db.Model, GlyphMixin):
# PK column and tablename etc. come from the mixin
area = db.Column(db.String(100), nullable=False, unique=True)
# association proxy
correspondents = association_proxy('tablet_correspondents', 'correspondent')
def __init__(self, area, correspondents=None):
self.area = area
if correspondents:
self.correspondents = correspondents
class Tablet_Correspondent(db.Model):
__tablename__ = "tablet_correspondent"
tablet_id = db.Column("tablet_id",
db.Integer(), db.ForeignKey("tablet.id"), primary_key=True)
correspondent_id = db.Column("correspondent_id",
db.Integer(), db.ForeignKey("correspondent.id"), primary_key=True)
# relations
tablet = db.relationship(
"Tablet",
backref="tablet_correspondents",
cascade="all, delete-orphan",
single_parent=True)
correspondent = db.relationship(
"Correspondent",
backref="correspondent_tablets",
cascade="all, delete-orphan",
single_parent=True)
def __init__(self, tablet=None, correspondent=None):
self.tablet = tablet
self.correspondent = correspondent
Ich kann Datensätze tablet
und correspondent
hinzufügen und dabei zum Beispiel gibt einfach eine leere Liste zurück, wie Sie es erwarten würden. Wenn ich manuell eine Zeile in meine tablet_correspondent
Tabelle unter Verwendung der vorhandenen IDs für Tablets und Korrespondenten einfüge, wird die Liste wie erwartet erneut ausgefüllt.
Wenn ich jedoch
cor = Correspondent.query.first()
tab = Tablet.query.first()
tab.correspondents.append(cor)
zu tun versuchen, erhalte ich:
KeyError: 'tablet_correspondents'
Ich bin mir ziemlich sicher, dass ich etwas ziemlich elementar hier auslassen.
Ich denke, Sie '__tablename__ =„tablet_correspondent“' falsch ist.Sollte es nicht "tablet_correspondents" sein (mit einem 's' am Ende)? –