如何在SQLAlchemy中为关系设置默认值?

时间:2016-07-08 03:13:16

标签: python database-design sqlalchemy relationship flask-sqlalchemy

我的用户模型中有一个关于Flask-SQLAlchemy项目的以下关系字段,我希望能够设置一个默认值,以便用户自动关注自己。有没有办法在SQLAlchemy中的关系中设置默认值?那会是什么样的?

getValue(DevicesCollection.class);

以下功能是:

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')

我一直在使用Miguel Grinberg的教程作为参考,但是我的项目已经设置好了,所以我不能像他那样在after_login中做db.session.add(user.follow(user))。我之前在before_first_request中完成了它,但是由于用户没有登录并因此匿名,因此单元测试存在问题。让用户在初始化时将自己作为默认值来解决这个问题。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

您的用户模型添加新方法。

@staticmethod
def follow():
  if not user.is_following(user):
        user.follow(user)
        db.session.add(user)
        db.session.commit()    
相关问题