Search code examples
pythondatabase-designsqlalchemyrelationshipflask-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. Is there a way to set a default value in relationships in SQLAlchemy at all? 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. I'd done it before in before_first_request but with unittesting have problems because the user is not logged in and thus anonymous. Having a user follow themselves as a default upon initialization would solve this. Thanks for the help!


Solution

  • 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()