Skip to main content

annotate() and aggregate() for generically related data

Project description

annotate() and aggregate() for generically-related data. also a handy function for filtering GFK-model querysets.

Use django’s GenericRelation where possible, as this can make the queries generated more efficient by using a JOIN rather than a subquery.

installation

# install from pypi
pip install django-generic-aggregation

# or install via git
pip install -e git+git://github.com/coleifer/django-generic-aggregation.git#egg=generic_aggregation

examples

The examples below assume the following simple models:

class Rating(models.Model):
    rating = models.IntegerField()
    object_id = models.IntegerField()
    content_type = models.ForeignKey(ContentType)
    content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id')

class Food(models.Model):
    name = models.CharField(max_length=50)
    ratings = generic.GenericRelation(Rating) # reverse generic relation

You want to figure out which items are highest rated (generic_annotate)

from django.db.models import Avg

food_qs = Food.objects.filter(name__startswith='a')
generic_annotate(food_qs, Rating, Avg('ratings__rating'))

# you can mix and match queryset / model
generic_annotate(food_qs, Rating.objects.all(), Avg('ratings__rating'))

You want the average rating for all foods that start with ‘a’ (generic_aggregate)

food_qs = Food.objects.filter(name__startswith='a')
generic_aggregate(food_qs, Rating, Avg('ratings__rating'))

You want to only display ratings for foods that start with ‘a’ (generic_filter)

food_qs = Food.objects.filter(name__startswith=’a’) generic_filter(Rating.objects.all(), food_qs)

documentation

http://django-generic-aggregation.readthedocs.org/

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-generic-aggregation-0.4.0.tar.gz (7.2 kB view details)

Uploaded Source

File details

Details for the file django-generic-aggregation-0.4.0.tar.gz.

File metadata

File hashes

Hashes for django-generic-aggregation-0.4.0.tar.gz
Algorithm Hash digest
SHA256 8cd40ab7d999dc20ffe853cd5770b3273d1611f26295c8932df31f1c6b48a72a
MD5 ab423b63bb05202c17b5b9a84bcb3b5d
BLAKE2b-256 819439b57c166613d2b7dcbc31e22672f13bfe9438e332d6e106899728b8a2bc

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page