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

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

我一直在使用 Miguel Grinberg 的教程作为参考,但我的项目设置使我无法在 after_login 中执行 db.session.add(user.follow(user)) 作为他是这样的。我以前在 before_first_request 做过,但是单元测试有问题,因为用户没有登录,因此是匿名的。让用户在初始化时将自己作为默认设置可以解决这个问题。感谢您的帮助!

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

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