[英]How do you display a views.py's variable linked to annotated queryset in a django template?
如何在Django模板中顯示鏈接到帶注釋的查詢集的views.py變量? 我知道帶注釋的查詢集在打印出來時會返回正確的數據,但是以某種方式,循環模板無法在html頁面上檢索數據。 有人可以建議我如何解決此問題嗎? 謝謝。
觀點
from django.shortcuts import render
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
from django.urls import reverse_lazy
from myapp.models import Pastry
from myapp.forms import PastryForm
from django.db.models import F
這行ps = Pastry.objects.values('pastry').annotate(total=Count('pastry'))
返回正確的數據:
{'pastry': 'Brownie', 'total': 1}
{'pastry': 'Cake', 'total': 1}
{'pastry': 'Cupcake', 'total': 1}
{'pastry': 'Fruit Tart', 'total': 1}
{'pastry': 'Muffin', 'total': 2}
class PollsListView(ListView):
model = Pastry
def get_queryset(self):
return Pastry.objects.all()
class PollsDetailView(DetailView):
model = Pastry
class PollsCreateView(CreateView):
success_url = reverse_lazy('pastry_list')
form_class = PastryForm
model = Pastry
class PollsUpdateView(UpdateView):
success_url = reverse_lazy('pastry_list')
form_class = PastryForm
model = Pastry
class PollsDeleteView(DeleteView):
model = Pastry
success_url = reverse_lazy('pastry_list')
pastry_list.html(模板)
{% extends "base.html" %}
{% block content %}
<div class="jumbotron">
<a href="{% url 'pastry_new' %}">New Poll</a>
<h1>Voting for the favorite pastry</h1>
Somehow this code here is not displaying any data.
{% for p in ps %}
{% for k, v in p.items %}
{{k}}{{v}}
{% endfor %}
{% endfor %}
{% for pastry in pastry_list %}
<div class="pastry">
<h3><a href="{% url 'pastry_detail' pk=pastry.pk %}">
{{ pastry.pastry }}</a></h3>
</div>
{% endfor %}
</div>
{% endblock %}
可以在文檔中找到更多信息
基本上,您可以通過get_context_data()
方法將更多變量發送到模板
樣品:
class PollsListView(ListView):
model = Pastry
def get_queryset(self):
return Pastry.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['ps'] = = Pastry.objects.values('pastry').annotate(total=Count('pastry'))
return context
使用get_context-data()
,您的變量ps
在模板pastry_list.html
可用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.