【问题标题】:How to set a default value for a relationship in SQLAlchemy?如何为 SQLAlchemy 中的关系设置默认值?
【发布时间】:2016-11-10 12:49:52
【问题描述】:

我的 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 中做过,但是单元测试有问题,因为用户没有登录,因此是匿名的。让用户在初始化时默认跟随自己可以解决这个问题。感谢您的帮助!

【问题讨论】:

  • 你的意思是......你不能在用户登录后更新你的User db?
  • @Iron 我的意思是我一直试图让用户默认关注自己,但在用户登录之前使用 current_user.follow(current_user) 进行操作(在@app.before_first_request 中) ,所以我引用了一个匿名用户。现在我正在尝试找到一种方法,以便登录用户默认跟随自己(或者每个用户默认跟随自己)

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-06-21
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2014-12-05
    • 2016-08-03
    相关资源
    最近更新 更多