Skip to content
Advertisement

Django-filter: count data

Does anybody knows how can I use count based on selected value using django_filters

Error

'UserFilter' object has no attribute 'count'

My Reference link

views.py

  def search(request):
      user_list = Person.objects.all()
      user_filter = UserFilter(request.GET, queryset=user_list)
      count = user_filter.count() #this will return an error
      print(count)
      return render(request, 'user_list.html', {'filter': user_filter})

filters.py

    from django.contrib.auth.models import User
    from .models import Person
    import django_filters
     
    class UserFilter(django_filters.FilterSet):
        class Meta:
            model = Person
            fields = ['category', 'firstname', 'lastname' ]

user_list.html

    {% extends 'base.html' %} 
    {% block content %}
      <form method="get">
        {{filter.form.as_p}}
          <button type="submit" >Search</button>
      </form>
      <table class="table table-bordered">
        <thead>
          <tr>
            <th>Firstname</th>
            <th> Lastname</th>
            <th>Caegory</th>
          </tr>
        </thead>
        <tbody>
          {% for user in filter.qs %}
            <tr>
              <td>{{ user.firstname }}</td>
              <td>{{ user.lastname }}</td>
              <td>{{ user.category }}</td>
            </tr>
          {% empty %}
            <tr>
              <td colspan="5">No data</td>
            </tr>
          {% endfor %}
        </tbody>
      </table>
    {% endblock %}

I want to count all the list base from data I filtered

enter image description here

Advertisement

Answer

You’ll want the count of the resulting queryset, which you can get from the filter’s qs property (as you do in your template!).

Change

count = user_filter.count()

to

count = user_filter.qs.count()
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement