Skip to main content
This is a pre-production deployment of Warehouse. Changes made here affect the production instance of PyPI (
Help us improve Python packaging - Donate today!

Group by arbitrary model fields

Project Description

This package provides a mixin for Django QuerySets that adds a method group_by that behaves mostly like the values method, but with one difference: its iterator does not return dictionaries, but a model-like object with model instances for related values.


Install from PyPI:

pip install django-group-by


This package is compatible with Django 1.8, 1.9 and 1.10, and Python versions 2.7, 3.4, 3.5 and 3.6. Probably others, but those 12 combinations are the ones against which we build (by Travis CI).


Create a QuerySet subclass with the GroupByMixin to use in a model’s manager:


from django.db import models
from django.db.models.query import QuerySet
from django_group_by import GroupByMixin

class BookQuerySet(QuerySet, GroupByMixin):

class Book(Model):
    objects = BookQuerySet.as_manager()

    title = models.CharField(max_length=100)
    author = models.ForeignKey('another_app.Author')
    publication_date = models.DateField()

Then use it just like values, and you’ll get a similar query set:

>>> some_rows = Book.objects.group_by('title', 'author', 'author__nationality').distinct()
>>> some_rows.count()

The difference is that every row is not a dictionary but an AggregatedGroup instance, with only the grouped fields:

>>> row = some_rows[0]
>>> row
<AggregatedGroup for Book>
>>> row.title
The Colour of Magic
>>> row.publication_date
*** AttributeError: 'AggregatedGroup' object has no attribute 'publication_date'

But of course the main advantage is that you also get related model instances, as far as you want:

<Author: Terry Pratchett>
>>> row.author_nationality
<Nation: Great Britain>

Release History

This version
History Node


History Node


History Node


History Node


History Node


History Node


History Node


Download Files

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

Filename, Size & Hash SHA256 Hash Help File Type Python Version Upload Date
(8.6 kB) Copy SHA256 Hash SHA256
Wheel py2.py3 Mar 12, 2017
(5.5 kB) Copy SHA256 Hash SHA256
Source None Mar 12, 2017

Supported By

Elastic Elastic Search Pingdom Pingdom Monitoring Dyn Dyn DNS Sentry Sentry Error Logging CloudAMQP CloudAMQP RabbitMQ Heroku Heroku PaaS Kabu Creative Kabu Creative UX & Design Fastly Fastly CDN DigiCert DigiCert EV Certificate Google Google Cloud Servers