神刀安全网

Retrieve average, minumum, maximum values from model field using Django Aggregation

Django queries helps to create, retrieve, update and delete objects. But some times we need to get summered values from the objects. Then Simple solution is to use Django aggregate feature Here are simple examples for how to use aggrigation.

app/models.py

class company(models.Model):      name=models.CharField(max_length=20)      est=models.IntegerField(max_length=4)  class feature(models.Model):      name=models.CharField(max_length=20)  class device(models.Model):      name=models.CharField(max_length=20)      Code=models.IntegerField()      Company=models.ForeignKey(company)      features=models.ManyToManyField(feature)

To perform Min Max and Avg on specific column

>>> from django.db.models import Avg, Max, Min, Sum >>> device.objects.all().aggregate(Avg('price'))     {'price__avg': 12234.0} >>> device.objects.all().aggregate(Max('price'))     {'price__max':587961 } >>> device.objects.all().aggregate(Min('price')) {'price__min': 01245}

To know the children count of a forignkey field.

>>> Comp_Devices=company.objects.annotate(no_of_devices=Count('device')) >>> Comp_Devices[0].no_of_devices 36 >>> Comp_Devices[0].name u'Micro' >>> Comp_Devices[1].no_of_devices 1

same procedure can be followed for ManyToMany field Columns

>>> Dev_features_count = device.objects.annotate(num=Count('features'))  >>> Dev_features_count[0].num  3  >>> Dev_features_count[1].num  2  >>> 

You can perform some complex queries like

To know the devices which has more than two features

>>> Dev_features= device.objects.annotate(num=Count('features')).filter(num__gt=2)  >>> Dev_features[0].num  3  >>> 

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Retrieve average, minumum, maximum values from model field using Django Aggregation

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址