Package: django-pivot
This package provides utilities for turning Django Querysets intoPivot-Tablesand Histograms
by letting your database do all the heavy lifting.ExamplesI am going to shamelessly lift examples from the wikipedia page referenced in the header.
Here is part of the table of shirt sales:RegionGenderStyleShip DateUnitsPriceCostEastBoyTee1/31/20051211.0410.42EastBoyGolf1/31/2005121312.6EastBoyFancy1/31/20051211.9611.74EastGirlTee1/31/20051011.2710.56EastGirlGolf1/31/20051012.1211.95EastGirlFancy1/31/20051013.7413.33WestBoyTee1/31/20051111.4410.94WestBoyGolf1/31/20051112.6311.73WestBoyFancy1/31/20051112.0611.51WestGirlTee1/31/20051513.4213.29WestGirlGolf1/31/20051511.4810.67Etc.We might want to know how manyUnitsdid we sell in eachRegionfor everyShip Date?
And get a result like:Region1/31/20052/1/20052/2/20052/3/20052/4/2005East668010293114North86919588107South7378847691West92103111104123It takes 3 quantities to pivot the original table into the summary result, two columns and
an aggregate of a third column. In this case the two columns are Region and Ship Date, the
third column is Units and the aggregate is SumBasic usageThe pivot functionPivot tables are generated by the pivot function, which takes a Model and 3 attribute names,
to make a pivot table like the example above:>>> pivot_table = pivot(ShirtSales, 'shipped', 'region', 'units')The result is a list of dictionaries. Each
dictionary has a key for the row (‘shipped’ dates in this case) and a key for every value
of the column (‘region’ in this case).>>> for record in pivot_table:
...     print(record)
... {u'West': 59, 'shipped': datetime.date(2004, 12, 24), u'East': 71, u'North': 115, u'South': 56}
... {u'West': 55, 'shipped': datetime.date(2005, 1, 31), u'East': 65, u'North': 121, u'South': 66}
... {u'West': 56, 'shipped': datetime.date(2005, 2, 1), u'East': 62, u'North': 124, u'South': 68}
... {u'West': 56, 'shipped': datetime.date(2005, 2, 2), u'East': 59, u'North': 127, u'South': 71}
... {u'West': 66, 'shipped': datetime.date(2005, 3, 1), u'East': 55, u'North': 131, u'South': 65}
... {u'West': 68, 'shipped': datetime.date(2005, 3, 2), u'East': 56, u'North': 130, u'South': 62}
... {u'West': 71, 'shipped': datetime.date(2005, 4, 3), u'East': 56, u'North': 130, u'South': 59}
... {u'West': 65, 'shipped': datetime.date(2005, 5, 6), u'East': 66, u'North': 120, u'South': 55}The first argument can be a Model, QuerySet, or Manager. This allows you to generate a pivot
table filtered by another column. For example, you may want to know how many units were sold
in each region for every shipped date, but only for Golf shirts:>>> pivot_table = pivot(ShirtSales.objects.filter(style='Golf'), 'region', 'shipped', 'units')The pivot function takes an optional parameter for how to aggregate the data. For example,
instead of the total units sold in each region for every ship date, we might be interested in
the average number of units per order. Then we can pass the Avg aggregation function>>> from django.db.models import Avg
>>> pivot_table = pivot(ShirtSales, 'region', 'shipped', 'units', aggregation=Avg)The pivot function can optionally include aTotalcolumn, containing all the data
aggregated to a single column:>>> pivot_table = pivot(ShirtSales.objects.filter(style='Golf'), 'region', 'shipped', 'units', include_total=True)If your data is stored across multiple tables, use Django’s double underscore notation
to traverse foreign key relationships. For example, instead of the ShirtSales model having
aregionattribute, it might have a foreign key to a Store model, which in turn has a
foreign key to a Region model, which has an attribute called name. Then our pivot call looks
like>>> pivot_table = pivot(ShirtSales, 'store__region__name', 'shipped', 'units')It’s also possible that the data column we are aggregating over should be a computed column.
In our example ShirtSales model we are storing the number of units and the price per
unit, but not the total cost of the order. If we want to know the average order size in
dollars in each region for every ship date, we can pivot the ShirtSales table:>>> from django.db.models import F, Avg
>>> pivot_table = pivot(ShirtSales, 'region', 'shipped', F('units') * F('price'), Avg)If the rows should be grouped on a compound column, for example, you want to know how manyUnitswere sold on each ship date not just split by region, but the combination of region
and gender, you can pass a list to the first argument:>>> pivot_table = pivot(ShirtSales, ['region', 'gender'], 'shipped', 'units')To change the way the row keys are displayed, a display_transform function can be passed to
the pivot function. display_transform is a function that takes an object and returns a string.
For example, instead of getting the results with North, East, South, and West for the regions
you want them all lower cased, you can do the following>>> def lowercase(s):
>>>     return s.lower()
>>> pivot_table = pivot(ShirtSales, 'region', 'shipped', 'units', display_transform=lowercase)The display_transform option is also useful if your column attribute is not a hashable type. Since it
will be used as a key in a dictionary, you need to do something to make it hashable, for
example converting it to its string representation:>>> pivot_table = pivot(ShirtSales, 'region', 'shipped', 'units', display_transform=str)If there are no records in the original data table for a particular cell in the pivot result,
SQL will return NULL and this gets translated to None in python. If you want to get zero, or
some other default, you can pass that as a parameter to pivot:>>> pivot_table = pivot(ShirtSales, 'region', 'shipped', 'units', default=0)The above call ensures that when there are no units sold in a particular region on a particular
date, we get zero as the result instead of None. However, the results will only contain
shipped dates if at least one region had sales on that date. If it’s necessary to get results
for all dates in a range including dates where there are no ShirtSales records, we can pass
a target row_range:>>> from datetime import date, timedelta
>>> row_range = [date(2005, 1, 1) + timedelta(days) for days in range(59)]
>>> pivot_table = pivot(ShirtSales, 'region', 'shipped', 'units', default=0, row_range=row_range)Will output a result with every shipped date from Jan 1st to February 28th whether there are
sales on those days or not.The histogram functionThis library also supports creating histograms from a single column of data with the
histogram function, which takes a Model, a single attribute name and an iterable of left edges
of bins.>>> hist = histogram(ShirtSales, 'units', bins=[0, 10, 15])Likepivot, the first argument can be a Model, QuerySet, or Manager. The result is a
list of dictionaries:>>> hist
[{'bin': '0', 'units': 0},
{'bin': '10', 'units': 0},
{'bin': '15', 'units': 0}]It’s also possible to get several histograms from a single query by slicing the data on one
of the columns. For example, instead of the histogram above, we might want two histograms,
one for boys and one for girls. Thegendercolumn ofShirtSaleshas two values,'Boy'and'Girl'. Passing the gender column as a 4th optional parameter to histogram
will slice the data on that column.>>> hist = histogram(ShirtSales, 'units', bins=[0, 10, 15], slice_on='gender')The result is a ValuesQuerySet where each row corresponds to one bin>>> for row in hist:
        print(row)
{'bin': u'0', u'Boy': 53, u'Girl': 53}
{'bin': u'10', u'Boy': 40, u'Girl': 41}
{'bin': u'15', u'Boy': 27, u'Girl': 26}InstallationJust:pip install django-pivotand then you:from django_pivot.pivot import pivot
from django_pivot.histogram import histogramAnd off you go.TestsThe test suite is run by via Github actions for pushes to master and pull requests to master
with Django versions 3.2.21, 4.1.11, and 4.2.5 and backends sqlite, MySQL, and Postgres. If you
want to run the test suite locally, from the root directory:python runtests.pyThat will use sqlite as the backend and whatever version of Django you have
in your current environment.LicenseMITCopyright 2017 - 2023 Brad MartsbergerPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.Contributorsrafal-jaworski