1
votes

I am following the example described in the book, Flask Web Development, by Miguel Grinberg.

I checked out at 12b (Chapter on Followers), but the app does not persist.

After changing the model it worked. However, I'm not sure, if it was the right way to go about it.

class User(UserMixin, db.Model):
    #...
    def follow(self, user):
        if not self.is_following(user):
            f = Follow(follower=self, followed=user)
            db.session.add(f)

after adding: db.session.commit() it worked, however, I might be missing something, as this is the first "error" that I encountered so far.

1

1 Answers

0
votes

No, adding a db.session.commit() in the follow() method is a workaround for your problem, but not a good idea.

A database commit should exist in the route function, at the end. The idea is that during the request all the changes are accumulated in the database session, and only at the end, when we are sure that the request was successful, a commit is made to make all those changes permanent.

I actually recorded a short video that includes a discussion on this idea of issuing a single commit at the very end of each request, so if you want to learn more about that see https://www.youtube.com/watch?v=5-4W3m5gRAs.

For your particular problem, you need to check why after the follow() method returns there is no commit in the main route function. Adding a commit there should fix your problem.