jpwatts / django-positions

A Django field for custom model ordering.

This URL has Read+Write access

jpwatts (author)
Thu Aug 13 11:18:15 -0700 2009
commit  9b3d6fa2c4fce2677ffaa38b47a63dd6ee9f2367
tree    5ced0668d230a23fa45e05d2aee9b97f73e84226
parent  1dcacc3cf86bffd48165852c301adba1206ee34e
name age message
file AUTHORS Loading commit data...
file LICENSE Mon Jul 14 23:42:47 -0700 2008 Added LICENSE file. [jpwatts]
file README
directory positions/
file setup.py
README
================
Django Positions
================

This module provides ``PositionField``, a model field for Django_ that allows
instances of a model to be sorted by a user-specified position.  Conceptually,
the field works like a list index: when the position of one item is changed, the
positions of other items in the collection are updated in response.


Usage
-----

Add a ``PositionField`` to your model; that's just about it.

If you want to work with all instances of the model as a single collection,
there's nothing else required.  In order to create collections based on another
field in the model (a ``ForeignKey``, for example), set ``unique_for_field`` to
the name of the field.

It's probably also a good idea to wrap the ``save`` method of your model in a
transaction since it will trigger another query to reorder the other members of
the collection.

Look at ``positions.example.models`` for an example of how to add
``PositionField`` to a model and at ``positions.example.tests`` for API usage.

Indices
~~~~~~~

In general, the value assigned to a ``PositionField`` will be handled like a
list index, to include negative values.  Setting the position to ``-2`` will
cause the item to be moved to the second position from the end of collection --
unless, of course, the collection has fewer than two elements.

Behavior varies from standard list indices when values greater than or less than
the maximum or minimum positions are used.  In those cases, the value is handled
as being the same as the maximum or minimum position, respectively.  ``None`` is
also a special case that will cause an item to be moved to the last position in
its collection.


Limitations
-----------

* Unique constraints can't be applied to ``PositionField`` because they break
  the ability to update other items in a collection all at once.  This one was
  a bit painful, because setting the constraint is probably the right thing to
  do from a database consistency perspective, but the overhead in additional
  queries was too much to bear.

* After a position has been updated, other members of the collection are updated
  using a single SQL ``UPDATE`` statement, this means the ``save`` method of the
  other instances won't be called.

.. _`Django`: http://www.djangoproject.com/