简体   繁体   English

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

[英]How to set a default value for a relationship in SQLAlchemy?

I have the following relationship field in my User model for a Flask-SQLAlchemy project and I want to be able to set a default value so that users are automatically following themselves. 在我的Flask-SQLAlchemy项目的用户模型中,我具有以下关系字段,并且我希望能够设置默认值,以便用户自动关注自己。 Is there a way to set a default value in relationships in SQLAlchemy at all? 有没有办法设置在所有的SQLAlchemy关系的默认值? What would that look like? 那会是什么样?

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

The follow function is this: 跟随功能是这样的:

    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

I've been using Miguel Grinberg's tutorial for reference but my project is set up so that I can't do db.session.add(user.follow(user)) in after_login as he does. 我一直在使用米格尔·格林贝格的教程供参考,但我的项目设置,让像他那样,我不能在after_login做db.session.add(user.follow(用户))。 I'd done it before in before_first_request but with unittesting have problems because the user is not logged in and thus anonymous. 我之前在before_first_request中就已经做到了,但是在单元测试中却遇到了问题,因为用户没有登录,因此是匿名的。 Having a user follow themselves as a default upon initialization would solve this. 在初始化时让用户遵循自己的默认设置将解决此问题。 Thanks for the help! 谢谢您的帮助!

your User Model add new method. 您的用户模型添加新方法。

@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM