【问题标题】:Can I get the property of a specific object in a Django template?我可以在 Django 模板中获取特定对象的属性吗?
【发布时间】: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


【解决方案1】:

这应该得到应该有标题的手稿对象:-

Manuscript.objects.get(id=ms)

注意 ms 是 get 参数中的 id(在您的示例中为 8)。

【讨论】:

  • 当然可以。我怎样才能在模板上得到它?
  • 在上下文中传递它。
猜你喜欢
  • 2011-04-19
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 2011-05-07
相关资源
最近更新 更多