【发布时间】:2021-04-17 17:38:43
【问题描述】:
我在我的项目中使用 django-filters。假设我在搜索后得到了这个地址:
?title=我的标题&ms=8
如您所见,我搜索了“我的标题”和用户视为“我的手稿”但其get 参数(和 ID)为 8 的手稿。
现在,我想在我的模板中添加一个礼貌的“您搜索过”字段。如何显示该手稿的标题而不是其 ID?
我的视图中已经有了 ms 对象:
mstunes = MsTune.objects.all()
ms = Manuscript.objects.all() <- manuscripts
f = MsTuneFilter(request.GET, queryset=MsTune.objects.all())
return render(request, 'manuscript/mstune_list.html', {'mstunes': mstunes, 'f': f, 'request':request, 'ms': ms})
我确实可以使用{{ms.all}} 访问它们。是否可以用伪代码做一些事情,例如:
show the ms.title of the ms object with id = request.GET.ms
?
我的看法:
def MsTuneList(request):
mstunes = MsTune.objects.all()
ms = Manuscript.objects.all() # can I get the ms.id from the request, with, say, request.ms, and then use it with get(id=ms)?
f = MsTuneFilter(request.GET, queryset=MsTune.objects.all())
return render(request, 'manuscript/mstune_list.html', {'mstunes': mstunes, 'f': f, 'request':request, 'ms': ms})
【问题讨论】:
-
in
request.GET是带有查询参数的网址。您可以从那里获取它们并将此值传递给模板。 -
request.GET.ms 的值为 8(见我的问题)。我想要一个标题。
-
在 ms 查询集上使用 filter 方法。
-
@hansTheFranz 请阅读我的问题并查看我的参数。 django-filter 产生一个 ms=id 参数。参数中没有“标题”。
-
@HBMCS hansTheFranz 已经为您提供了正确的输入。从 GET 参数中获取 ms 参数,例如
get_ms = request.GET.get("ms")。然后可以筛选出具体的稿件searched_ms = Manuscript.objects.get(id=get_ms)。最后,您可以将此对象传递给您的渲染方法中的模板,并在模板中显示标题,如{{ serached_ms.title }}。
标签: django django-views django-templates django-filter