[英]How to set the default value of a column in sqlalchemy to the value of a column from a relationship?
[英]How to set a default value for a relationship in SQLAlchemy?
在我的Flask-SQLAlchemy項目的用戶模型中,我具有以下關系字段,並且我希望能夠設置默認值,以便用戶自動關注自己。 有沒有辦法設置在所有的SQLAlchemy關系的默認值? 那會是什么樣?
followed = db.relationship('User', secondary=followers, primaryjoin=(followers.c.follower_id == id),
secondaryjoin=(followers.c.followed_id == id),
backref=db.backref('followers', lazy='dynamic'),
lazy='dynamic')
跟隨功能是這樣的:
def follow(self, user):
# returns an object if it succeeds, None if it fails
if not self.is_following(user):
self.followed.append(user)
return self
我一直在使用米格爾·格林貝格的教程供參考,但我的項目設置,讓像他那樣,我不能在after_login做db.session.add(user.follow(用戶))。 我之前在before_first_request中就已經做到了,但是在單元測試中卻遇到了問題,因為用戶沒有登錄,因此是匿名的。 在初始化時讓用戶遵循自己的默認設置將解決此問題。 謝謝您的幫助!
您的用戶模型添加新方法。
@staticmethod
def follow():
if not user.is_following(user):
user.follow(user)
db.session.add(user)
db.session.commit()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.