【问题标题】:How to get a backref on Association Object - ie user.follows() and user.followers()如何获得关联对象的反向引用 - 即 user.follows() 和 user.followers()
【发布时间】:2019-11-06 14:29:56
【问题描述】:

我正在尝试创建一个关联对象UserRelationship,它定义了UserUser 之间的“关注”关系。

class UserRelationship(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    follows_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    follower_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    follows = db.relationship("User", foreign_keys=[follows_id])
    follower = db.relationship("User", foreign_keys=[follower_id])
    bank = db.Column(db.Float)

    def __repr__(self):
        return f'{self.follower.username} follows {self.follows.username} with {self.bank}'



class User(UserMixin, db.Model):

    follows = db.relationship('UserRelationship',
                              primaryjoin=(UserRelationship.follower_id == id),
                              backref=db.backref('followers'),
                              lazy='dynamic')

    def follow(self, user, bank):
        if not self.is_following(user):
            new_follow = UserRelationship(bank=bank)
            new_follow.follows = user
            self.follows.append(new_follow)
            db.session.commit()
            return new_follow

    def unfollow(self, user):
        if self.is_following(user):
            relationship = self.follows.filter(UserRelationship.follows == user).first()
            db.session.delete(relationship)
            db.session.commit()
            return self.follows.all()

    def is_following(self, user):
        return self.follows.filter(
            UserRelationship.follows == user).count() > 0

这会在 shell 中产生预期的结果:

joe=User(username='joe')
paul=User(username='paul')
phil=User(username='phil')

phil.follow(joe,bank=123)
[phil follows joe with 123]


因此,当我使用 User.follows 时,我会被带到一个 UserRelationship 对象,我可以查询该对象以获取该用户关注的所有人。我明白了。我无法理解的是如何让 User.followers 工作。我想要的是查询(或列表)或 User.followers。 backref 命令不起作用 = 在控制台中输入 'phil.followers' 会产生

Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'User' object has no attribute 'followers'

也许我可以写一个函数?但是我不完全确定要写什么来查询数据库以获取所有关注特定用户的用户列表。

【问题讨论】:

    标签: python flask


    【解决方案1】:

    我想通了——其实很简单:

        def followers(self):
            return UserRelationship.query.filter_by(follows=self).all()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      • 2010-11-26
      • 1970-01-01
      相关资源
      最近更新 更多