ramesh patil
ramesh patil

Reputation: 47

count and sort according to column value in django query

django model

class Report_Shop(models.Model):
barcode = models.CharField(max_length=500)
email = models.CharField(max_length=500)
shop_name = models.CharField(max_length=500)

above model multiple entries of one shop_name allow

how to count same value of shop_name ???

shop_count i.e. number of shop name (avoid repeated) -> example 3

s_name i.e. shop name -> 1.yyy 2.xxx 3.zzzz

no_reports i.e. number of entries of shop name

-> 1.yyy (3)
-> 2.xxx (11)
-> 3.zzz (5)

give me some advise for better response, thanks in advance !!!

Upvotes: 0

Views: 351

Answers (2)

avd
avd

Reputation: 318

Report_Shope.objects.values('shop_name').annotate(
   shop_count=Count('id')
).order_by('shop_count')

Aggregation docs.

Upvotes: 1

You can use count()

Report_Shop.objects.filter(barcode='value').count()

and to sort you can add meta in your model to default order

class Report_Shop(models.Model):
    barcode = models.CharField(max_length=500)
    email = models.CharField(max_length=500)
    shop_name = models.CharField(max_length=500)

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

or in your queryset with orfer_by()

Report_Shop.objects.order_by('barcode')
Report_Shop.objects.order_by('-barcode')

The negative sign in front of "-barcode" indicates descending order. Ascending order is implied. To order randomly, use "?".

Upvotes: 0

Related Questions