我想设计一个具有用户和项目的应用程序,用户可以是项目的候选者,并且可以选择作为项目的参与者。所以我使用下面的代码:
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')
然后我尝试在shell中创建一些数据:
# 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的新手,设计数据库的正确方法是什么?
答案 0 :(得分:0)
candidate_id
和participant_id
属性是用户外键。您正在与Project表建立关系。您需要将它们移动到User表,然后它们才能正常工作。
然后,如果您需要获得项目的所有候选人或参与者,您可以使用这些关系并按您感兴趣的项目过滤它们。