0
我想要設計這樣一個具有用戶和項目的應用程序,用戶可以是項目的候選人,並且可以選擇作爲項目的參與者。所以我用下面的代碼:flask-sqlalchemy中的關聯表
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True)
class Participate(db.Model):
__tablename__ = 'participates'
project_id = db.Column(db.Integer, db.ForeignKey('projects.id'),
primary_key=True)
candidate_id = db.Column(db.Integer, db.ForeignKey('users.id'),
primary_key=True)
participant_id = db.Column(db.Integer, db.ForeignKey('users.id'),
primary_key=True)
candidate_timestamp = db.Column(db.DateTime, default=datetime.utcnow)
participate_timestamp = db.Column(db.DateTime, default=datetime.utcnow)
class Project(db.Model):
__tablename__ = 'projects'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
candidates = db.relationship('Participate',
foreign_keys=[Participate.candidate_id],
backref=db.backref('candidate_projects', lazy='joined'),
lazy='dynamic')
participants = db.relationship('Participate',
foreign_keys=[Participate.participant_id],
backref=db.backref('participate_projects', lazy='joined'),
lazy='dynamic')
然後我試圖在殼創建一些數據:
# python manage.py shell
>>> db
<SQLAlchemy engine='mysql://connection_uri?charset=utf8&use_unicode=0'>
>>> Project
<class 'app.models_.Project'>
>>> User
<class 'app.models_.User'>
>>> Participate
<class 'app.models_.Participate'>
>>> jerry = User(username='jerry')
我得到這個異常:
NoForeignKeysError: Could not determine join condition between parent/child
tables on relationship Project.candidates - there are no foreign keys linking
these tables. Ensure that referencing columns are associated with a ForeignKey
or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
我是新來的SQLAlchemy,像我想要的那樣設計數據庫的正確方法是什麼?