Django Pivot-Tables
===================

This package provides utilities for turning Django Querysets into
`Pivot-Tables <https://en.wikipedia.org/wiki/Pivot_table>`_ and Histograms
by letting your database do all the heavy lifting.

.. image:: https://codecov.io/gh/martsberger/django-pivot/branch/master/graph/badge.svg
  :target: https://codecov.io/gh/martsberger/django-pivot

.. image:: https://img.shields.io/pypi/dm/django-pivot.svg
    :target: https://pypistats.org/packages/django-pivot

Examples
--------

I am going to shamelessly lift examples from the wikipedia page referenced in the header.
Here is part of the table of shirt sales:

======  ======  ====== ========== ====== ====== ======
Region  Gender  Style  Ship Date   Units  Price  Cost
======  ======  ====== ========== ====== ====== ======
East    Boy     Tee     1/31/2005     12  11.04  10.42
East    Boy     Golf    1/31/2005     12     13   12.6
East    Boy     Fancy   1/31/2005     12  11.96  11.74
East    Girl    Tee     1/31/2005     10  11.27  10.56
East    Girl    Golf    1/31/2005     10  12.12  11.95
East    Girl    Fancy   1/31/2005     10  13.74  13.33
West    Boy     Tee     1/31/2005     11  11.44  10.94
West    Boy     Golf    1/31/2005     11  12.63  11.73
West    Boy     Fancy   1/31/2005     11  12.06  11.51
West    Girl    Tee     1/31/2005     15  13.42  13.29
West    Girl    Golf    1/31/2005     15  11.48  10.67
Etc.
======  ======  ====== ========== ====== ====== ======

We might want to know how many *Units* did we sell in each *Region* for every *Ship Date*?
And get a result like:

======== ========= ========= ========= ========= =========
Region   1/31/2005 2/1/2005  2/2/2005  2/3/2005  2/4/2005
======== ========= ========= ========= ========= =========
East            66        80       102        93       114
North           86        91        95        88       107
South           73        78        84        76        91
West            92       103       111       104       123
======== ========= ========= ========= ========= =========

It 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 Sum


Basic usage
-----------

*The pivot function*

Pivot 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 a *Total* column, 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
a *region* attribute, 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 many
*Units* were 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 function*

This 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])

Like *pivot*, 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. The ``gender`` column of ``ShirtSales`` has 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}


Installation
------------

Just::

    pip install django-pivot

and then you::

    from django_pivot.pivot import pivot
    from django_pivot.histogram import histogram

And off you go.


Tests
-----

The 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.py

That will use sqlite as the backend and whatever version of Django you have
in your current environment.

License
-------

MIT

Copyright 2017 - 2023 Brad Martsberger

Permission 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.

Contributors
------------

`rafal-jaworski <https://github.com/rafal-jaworski>`_
