3 回答
TA贡献1865条经验 获得超7个赞
您可以在函数外部声明列表 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})
TA贡献1812条经验 获得超5个赞
您可以编写一个可供两个视图使用的实用函数,并存储当前会话的数据:
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']
TA贡献1884条经验 获得超4个赞
您必须记住,无论您设置什么变量,它都只存在于视图/函数中,因为 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")
添加回答
举报