我仍然在控制SQLalchemy中的关系,我一直坚持下去。我正在尝试在用户之间添加关系作为朋友。我已经在路由中编码了一个查询,当我试图将用户对象添加到对象的关系属性(to_contacts)时,就会出现问题。
这是User对象:
class User(UserMixin, db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.VARCHAR(100), nullable=False)
first_name = db.Column(db.VARCHAR(45), nullable=False)
last_name = db.Column(db.VARCHAR(45), nullable=False)
email = db.Column(db.VARCHAR(100), unique=True, nullable=False)
password = db.Column(db.CHAR(64))
to_contacts = association_proxy('to_relations', 'to_contact', creator=lambda to_contact: Friends(to_contact=to_contact, relation_type='Friend'))
from_contacts = association_proxy('from_relations', 'from_contact')
关联代理引用的是自引用对象Friend:
class Friends(db.Model):
__tablename__ = 'friends'
id = db.Column(db.Integer, primary_key=True)
from_contact_id = db.Column(db.Integer, db.ForeignKey('user.id'))
to_contact_id = db.Column(db.Integer, db.ForeignKey('user.id'))
relation_type = db.Column(db.String(100), nullable=True)
from_contact = db.relationship(User,
primaryjoin=(from_contact_id == User.id),
backref='to_relations')
to_contact = db.relationship(User,
primaryjoin=(to_contact_id == User.id),
backref='from_relations')
出于测试目的,我已将添加的user2作为朋友硬编码为以下路线中的user1:
@app.route("/add-friend", methods=['GET', 'POST'])
def add_friend():
user1 = User.query.filter_by(username='user1').first()
user2 = User.query.filter_by(username='user2').first()
query = user1.to_contacts.append(user2)
db.session.add(query)
db.session.commit()
return url_for('index')
“查询”出了错。实际上,我可以获取User对象并读取任何属性,但是当to_contacts被寻址时,它似乎无法识别它是否映射到关系。
我在这里做什么错了?