【问题标题】:Can't remove objects from list after MySQL query with peewee in Flask在 Flask 中使用 peewee 进行 MySQL 查询后无法从列表中删除对象
【发布时间】:2015-12-02 21:54:27
【问题描述】:

我的网站主页上有几个链接,这些链接指向我列出一些团队新闻(标题和链接列表)的子页面。

当用户点击/Nba-Teams/Lakers时,他/她将在第一时间被转发到一切正常的新视图(我列出了有关湖人队的相关新闻),但当用户返回主页并单击/Nba-Teams/Spurs 链接它也可以工作,但我认为列表将始终包含以前的内容。

就像每次调用查询时,以前的结果都不会从teamNews 列表中消失。我真的是 Python 的新手,所以如果有人能告诉我我做错了什么,我将不胜感激。

我假设在我加载新页面时teamNews 不会为空,但不幸的是我无法确定。如您所见,在将数据传递给 html 后,我试图立即删除它的内容,但没有任何反应。

由于 html 使用 nbaTeamNews 变量的内容,我不确定这是否是 HTML 格式问题。

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 %}

【问题讨论】:

    标签: python flask peewee


    【解决方案1】:

    不,您无法到达del teamNews 行,因为您已经返回了响应,因此之前的结果仍然存在。

    相反,您可以这样做:

    # 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 
    

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多