在使用关联表中的附加字段设置多对多关系时遇到很多麻烦。我觉得我和这个人很接近,但我得到一个sqlite3.operational错误,说tbl_contacts.contact不存在。
有人能给我一些关于我做错的线索吗?
以下是代码:
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy import orm
import uuid
Base = declarative_base()
Session = orm.sessionmaker()
Engine = sa.create_engine('sqlite:///arandomdb', echo=True)
Session.configure(bind=Engine)
session = Session()
class TblEvents(Base):
__tablename__ = 'tbl_events'
guid = sa.Column(sa.String(36), primary_key=True, nullable=False)
name = sa.Column(sa.String)
contacts = orm.relationship('TblContacts', secondary='tbl_events_contacts', backref='events')
class TblContacts(Base):
__tablename__ = 'tbl_contacts'
guid = sa.Column(sa.String(36), primary_key=True, nullable=False)
name = sa.Column('contact', sa.String)
class TblEventsContacts(Base):
__tablename__ = 'tbl_events_contacts'
event_id = sa.Column(sa.String, sa.ForeignKey(TblEvents.guid), primary_key=True)
contact_id = sa.Column(sa.String, sa.ForeignKey(TblContacts.guid), primary_key=True)
primary = sa.Column(sa.Boolean)
event = orm.relationship('TblEvents',
backref=orm.backref('tbl_events_contacts',
passive_deletes='all'
))
contact = orm.relationship('TblContacts',
backref=orm.backref('events_assoc',
passive_deletes='all'))
if __name__ == '__main__':
Base.metadata.create_all(Engine)
ev1 = TblEvents(guid=str(uuid.uuid4()), name='event 1')
con1 = TblContacts(guid=str(uuid.uuid4()), name='contact 1')
session.add(ev1, con1)
session.commit()
ev1.contacts.append(con1)
session.commit()
这是错误:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: tbl_contacts.contact [SQL: 'SELECT tbl_contacts.contact AS tbl_contacts_contact, tbl_contacts.guid AS tbl_contacts_guid \nFROM tbl_contacts, tbl_events_contacts \nWHERE ? = tbl_events_contacts.event_id AND tbl_contacts.guid = tbl_events_contacts.contact_id'] [parameters: ('889ff3f2-d2bd-4e3e-b71d-cef224c3c671',)] (Background on this error at: http://sqlalche.me/e/e3q8)
答案 0 :(得分:0)
这条线错了:
name = sa.Column('contact', sa.String)
应该是:
name = sa.Column(sa.String)