Django数据保存和呈现

时间:2018-10-24 05:41:25

标签: python django

我的Django项目需要在使用views.py的一个函数处理后获取一个列表。

def acquire(request):
    import sys
    n = []
    for topic in Topic.objects.filter(owner=request.user).order_by("date_added"):
        entries = topic.entries.all()
        q = entries.text
        n.append(q)
    return render(request, "projects/topics.html", n)

上面的列表“ n”需要转移到views.py的另一个函数中,以获取另一个“ results.html”页面中的信息。

def results(request):
    data = XXXX
    return render(request, "projects/results.html", {"datas": data})

如何在结果函数中编辑“ XXX”以转移“ n”列表?

3 个答案:

答案 0 :(得分:1)

您可以编写一个实用程序函数,供两个视图使用,并存储当前会话的数据:

def acquire(request):
    data = _get_data(request)
    return render(request, "projects/topics.html", {'data': data})

def results(request):
    data = _get_data(request)
    return render(request, "projects/results.html", {'data': data})

# this is not a view, but a utility function
def _get_data(request)
    # this will try to use the data generated in a previous request of
    # the same session. So the data might be stale by now
    if not 'user_entries' in request.session:
        n = []
        for topic in Topic.objects\
                      .filter(owner=request.user)\
                      .order_by('date_added')\
                      .prefetch_related('entries'):  # prefetch avoids the nested queries
            for entry in topic.entries.all():
                n.append(entry.text)
        request.session['user_entries'] = n
    return request.session['user_entries']

答案 1 :(得分:0)

您可以在函数外部声明列表n,以便可以在任何需要的地方使用它,例如:

n = []

def acquire(request):
    import sys
    for topic in Topic.objects.filter(owner=request.user).order_by("date_added"):
        entries = topic.entries.all()
        q = entries.text
        n.append(q)
    return render(request, "projects/topics.html", n)

def results(request):
    data = n
    return render(request, "projects/results.html", {"datas": data})

答案 2 :(得分:0)

您必须记住,无论您设置什么变量,它都只能存在于视图/函数中,因为Django是无状态的。这就是为什么您有数据库和cookie。

这就是您的操作方式。除非该列表有成千上万的条目,否则速度会很快。

def results(request):
    data = []
    for topic in Topic.objects.filter(owner=request.user).order_by("date_added"):
        entries = topic.entries.all()
        q = entries.text
        data.append(q)
    return render(request, "projects/results.html", {"datas": data})

如果您想提高速度,可以更改请求并在数据库级别上工作并创建联接。与此类似的东西(我有点生锈)

data = Entries.objects.filter(topic__owner=request.user).order_by("topic__date_added").values("text")