title: Flask-SQLAlchemy changes don't persist
body: <p>I'm making a web application, where user action can affect some bar graphs (seen in the gif below). Sometimes, changes aren't saved. When I reload the page, the changed bar graphs are shown (indicating that the user's action's were saved). When I reload the page again, sometimes the updated bar graphs and corresponding list are shown. Other times, they are not.</p>
  
  <p><a href="https://i.stack.imgur.com/DGatn.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DGatn.gif" alt="The bug in action"></a></p>
  
  <p>Here's the code for the view:</p>
  
  <pre><code>@app.route('/')
  def home():
      '''homepage for application'''
  
      # redirect users who go to home page but aren't logged in
      if not current_user.is_authenticated:
          return redirect(url_for("landing"))
  
      # reset the session
      db.session.flush()
  
      # get most recent entered weight
      try:
          last_weight = WeightEntry.query.filter_by(user_id = current_user.user_id).order_by(WeightEntry.date)[-1]
      except IndexError:
          return error("No weight recorded. Please contact support.")
  
      return render_template("home.html",
                              today= Today(current_user.user_id),
                              foods = [food for food in FoodEntry.query.filter_by(user_id=current_user.user_id).all() if food.is_today() == True],
                              options =  sorted(Food.query.filter(Food.user_id==current_user.user_id).all(), key=lambda x: x.name),
                              last_weight = last_weight)
  </code></pre>
  
  <p>I added the <code>db.session.flush()</code> in an attempt to solve the problem, but that didn't work.</p>
  
  <p>The changes (logged foods) are stored here:</p>
  
  <pre><code>@app.route("/log_food", methods=["POST", "GET"])
  @login_required
  def log_food():
      # add foods given by the user
      if request.method == "POST":
          for food in request.form.getlist("logged_food"):
              try:
                  added_food = Food.query.filter_by(user_id=current_user.user_id, name=food).first()
                  x = FoodEntry(
                      food_id = added_food.food_id,
                      user_id = current_user.user_id)
                  db.session.add(x)
                  db.session.commit()
              except:
                  return error("Unable to log food.")
  
          return redirect(url_for("home"))
  </code></pre>
  
  <p>I'd appreciate any help I can get.</p>
  
  <p>Thanks!</p>