列表视图模板中的django count queryset字段

问题描述 投票:0回答:2

我坚持的问题。

我想要计算等于Active的venlist.Status并在某些html标签中显示它

如果您需要有关我的问题的更多详细信息,请通知我,因为这是我的第一篇文章,并且几乎在4小时内在图书馆中搜索它

models.朋友

VendorCH= [
    ('Active', 'Active'),
    ('BlackList', 'BlackList'),
]

class VendorModel(models.Model):
    Name=models.CharField(unique=True,max_length=40)
    President=models.CharField(unique=True,max_length=40)
    Status=models.CharField(max_length=40,choices=VendorCH,default='Active')

forms.朋友

class VendorForm(forms.ModelForm):
    class Meta:
        model = VendorModel
        exclude=['VendorStatus']

views.朋友

class VendorCreateView(SuccessMessageMixin,CreateView):
    template_name = "ePROC/Administration/Vendor_Create.html"
    model=VendorModel

    fields=['Name','President']
    success_message = "Record was created successfully"
    success_url = reverse_lazy('ePROC:ePROCHOME')

    def form_valid(self, form):
        form.instance.Status = 'Active'
        return super(VendorCreateView, self).form_valid(form)

List_Template.html

<table class="table table-hover">
<thead>
    <th> Vendor Name</th>
    <th> President</th>
    <th> Status</th>                                        
</thead>
<tbody>
{% for venlist in object_list %}
   <tr> 
       <td>{{ venlist.VendorName }}</td>
       <td>{{ venlist.President}}</td>
       <td>{{ venlist.Status}}</td>                                     
   </tr>
{% endfor %}
<tbody>
</table>
python django django-templates django-views
2个回答
0
投票
from django.views.generic.list import ListView

class VenderListView(ListView):
    queryset=VendorModel.objects.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['total_active_records'] = self.queryset.filter(Status='Active').count()
        return context

List_Template.html:

<div>Total Active Vendors: <span> {{ total_active_records }}</span></div> 

0
投票

这对我有用,基于Umar Asghar's answer

class IndexListView(ListView):
    template_name = "ePROC/Base/index.html"
    model = CreateReqModel
    context_object_name = 'reqlists'
    queryset=CreateReqModel.objects.all()
    paginate_by = 10

    def get_context_data(self, **kwargs):
        context = super(IndexListView, self).get_context_data(**kwargs)
        context['total_active_records'] = self.queryset.filter(Status='Initiate').count()
        context['range'] = range(context["paginator"].num_pages)
        return context
© www.soinside.com 2019 - 2024. All rights reserved.