How to get object name and object count using Django

96 views Asked by At

I want this kind of thing to display in HTML page

Location name Count

London 10

Manila 8

Location Name is in the database. I want to display the location name and how many times that location name was repeated.

view.py...

class MapListView(ListView):
    model = Map

      def get_queryset(self):


       return Map.objects.annotate(LocName_count=Count('LocName')).order_by('-LocName_count')[:9]

map_list.HTML...

{% for object in object_list %}
<tr>

    <td>{{object}}</a></td>
    <td><a href="{{object.get_absolute_url}}">{{ object.LocName }}</a></td>
    <td><a href="{{object.get_absolute_url}}">{{ object.LocName_count }}</a></td>


</tr>


{% endfor %}

models.py...

class Map(models.Model):

    # Fields
    LocName = models.TextField(max_length=255)


    class Meta:
        ordering = ('-pk',)

    def __unicode__(self):
        return u'%s' % self.pk

    def get_absolute_url(self):
        return reverse('Home_map_detail', args=(self.pk,))


    def get_update_url(self):
        return reverse('Home_map_update', args=(self.pk,))

I used like above but it not working Please help

2

There are 2 answers

6
Satendra On BEST ANSWER

You can use .values() and then .annotate() of django ORM for GROUP BY query

Map.objects.values('LocName').annotate(count=Count('LocName'))

the output will be

[
 {'LocName': 'London', 'count': 10}, 
 {'LocName': 'Manila', 'count': 8}
]

You can now easily loop over it in your template.

8
Samuel Omole On

You can just use the count() to get a count of the data, but can u show your whole model code to be sure