Search code examples
pythonflaskpeewee

Can't remove objects from list after MySQL query with peewee in Flask


I have a couple of links on my website's homepage, that links to subpages where I list some team news (list of titles and links).

When the user click on the /Nba-Teams/Lakers he/she will be forwarded to a new view where everything works fine (I list the related news about Lakers) at the first time, but when the user goes back to the homepage and clicks the /Nba-Teams/Spurs link it will also work, but the list in my view will always contain the previous content.

It's like everytime when the query is called the previous results aren't disappear from the teamNews list. I'm really new in Python so I would really appreciate if somebody could show me what I'm doing wrong.

I assume that the teamNews doesn't get nulled when I load a new page, but unfortunately I couldn't make it sure. As you can see I've tried to remove it's content right after I passed the data to the html, but nothing happens.

Since the html uses the content of the nbaTeamNews variable, I´m unsure if it's a HTML formatting issue.

teamNews = []

def getTeamNews (team_to_query):

    for obj in teams.select().where(teams.Nba == team_to_query):
        teamNews.append(obj)
    return teamNews    

@app.route('/Nba-Teams/<team>')
def team_page(team):

    return render_template("teams.html", nbaTeamNews=getTeamNews(team))
    del teamNews

html:

{% block body %}
<ul class=entries>
  {% for entry in nbaTeamNews %}
    <li><h2><a href="{{ entry.slug }}">{{ entry.newsTitle }}</a></h2>
  {% else %}
    <li><em>Unbelievable.  No entries here so far</em>
  {% endfor %}
  </ul>
{% endblock %}

Solution

  • No, you can't reach the del teamNews line, because you've already return the response, thus the previous results still lies there.

    Instead, you can do this way:

    # No teamNews here.
    
    def getTeamNews(team_to_query):
        # Since you don't do any other things, directly assign it is enough, right?
        # No need for a list comprehension or a for loop here.
        teamNews = teams.select().where(teams.Nba == team_to_query)
        return teamNews