Skip to main content

Drop-in replacement for django's many to many field with sorted relations.

Project description

PyPI Release Build Status

sortedm2m is a drop-in replacement for django’s own ManyToManyField. The provided SortedManyToManyField behaves like the original one but remembers the order of added relations.

Usecases

Imagine that you have a gallery model and a photo model. Usually you want a relation between these models so you can add multiple photos to one gallery but also want to be able to have the same photo on many galleries.

This is where you usually can use many to many relation. The downside is that django’s default implementation doesn’t provide a way to order the photos in the gallery. So you only have a random ordering which is not suitable in most cases.

You can work around this limitation by using the SortedManyToManyField provided by this package as drop in replacement for django’s ManyToManyField.

Requirements

django-sortedm2m runs on Python 2.6, 2.7, 3.2 and up. PyPy is supported as well. Django 1.6 and up is required.

Usage

Use SortedManyToManyField like ManyToManyField in your models:

from django.db import models
from sortedm2m.fields import SortedManyToManyField

class Photo(models.Model):
    name = models.CharField(max_length=50)
    image = models.ImageField(upload_to='...')

class Gallery(models.Model):
    name = models.CharField(max_length=50)
    photos = SortedManyToManyField(Photo)

If you use the relation in your code like the following, it will remember the order in which you have added photos to the gallery.

gallery = Gallery.objects.create(name='Photos ordered by name')
for photo in Photo.objects.order_by('name'):
    gallery.photos.add(photo)

SortedManyToManyField

You can use the following arguments to modify the default behavior:

sorted

Default: True

You can set the sorted to False which will force the SortedManyToManyField in behaving like Django’s original ManyToManyField. No ordering will be performed on relation nor will the intermediate table have a database field for storing ordering information.

sort_value_field_name

Default: 'sort_value'

Specifies how the field is called in the intermediate database table by which the relationship is ordered. You can change its name if you have a legacy database that you need to integrate into your application.

Migrating a ManyToManyField to be a SortedManyToManyField

If you are using Django’s migration framework and want to change a ManyToManyField to be a SortedManyToManyField (or the other way around), you will find that a migration created by Django’s makemigrations will not work as expected.

In order to migrate a ManyToManyField to a SortedManyToManyField, you change the field in your models to be a SortedManyToManyField as appropriate and create a new migration with manage.py makemigrations. Before applying it, edit the migration file and change in the operations list migrations.AlterField to AlterSortedManyToManyField (import it from sortedm2m.operations). This operation will take care of changing the intermediate tables, add the ordering field and fill in default values.

Admin

SortedManyToManyField provides a custom widget which can be used to sort the selected items. It renders a list of checkboxes that can be sorted by drag’n’drop.

To use the widget in the admin you need to add sortedm2m to your INSTALLED_APPS settings, like:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',

    'sortedm2m',

    '...',
)

Otherwise it will not find the css and js files needed to sort by drag’n’drop.

Finally, make sure not to have the model listed in any filter_horizontal or filter_vertical tuples inside of your ModelAdmin definitions.

If you did it right, you’ll wind up with something like this:

http://i.imgur.com/HjIW7MI.jpg

It’s also possible to use the SortedManyToManyField with admin’s raw_id_fields option in the ModelAdmin definition. Add the name of the SortedManyToManyField to this list to get a simple text input field. The order in which the ids are entered into the input box is used to sort the items of the sorted m2m relation.

Example:

from django.contrib import admin

class GalleryAdmin(admin.ModelAdmin):
    raw_id_fields = ('photos',)

Contribute

You can find the latest development version on github. Get there and fork it, file bugs or send me nice wishes.

Running the tests

I recommend to use tox to run the tests for all relevant python versions all at once. Therefore install tox with pip install tox, then type in the root directory of the django-sortedm2m checkout:

tox

However using tox will not include the tests that run against a PostgreSQL database. The project therefore contains a Vagrantfile that uses vagrant to setup a virtual machine including a working PostgreSQL installation. To run the postgres tests, please install vagrant and then run:

make test-postgres

This will bring up and provision the virtual machine and runs the testsuite against a PostgreSQL database.

Get in touch

Feel free to drop me a message about critique or feature requests. You can get in touch with me by mail or twitter.

Changelog

1.3.1

  • #57 & #81: Fix add related object popup error prevents operation when no related objects already exist. Thanks to Vadim Sikora for the fix.

1.3.0

  • #79: Use .sortedm2m-item selector in the widget’s JavaScript code to target the list items. This was previously ul.sortedm2m li. This improves compatibility other markup that does not want to use ul/li tags. Thanks to Michal Dabski for the patch.

    Note: If you use custom markup with the JavaScript code, you need to make sure that the items now have the sortedm2m-item class name.

  • #76: Add support for to_field_name to SortedMultipleChoiceField. Thanks to Conrad Kramer for the patch.

1.2.2

  • #75: Fix “add another” admin popup. It didn’t refresh the list of items in Django 1.8+. Thanks to Vadim Sikora for the patch.

1.2.1

  • skipped

1.2.0

  • Dropping Python 3.2 support. It has reached end of life in February 2016.

1.1.2

  • #71: Don’t break collectstatic for some cases. Therefore we removed the STATIC_URL prefix from the form media definition in SortedCheckboxSelectMultiple. Thanks to Kirill Ermolov for the patch.

1.1.1

  • #70: CSS fix for Django 1.9 new admin design. Thanks to Maarten Draijer for the patch.

1.1.0

  • #59, #65, #68: Django 1.9 support. Thanks to Scott Kyle and Jasper Maes for patches.

  • #67: Support for disabling migrations for some models, that can be decided by Django’s DB router (with the allow_migrate_model method). Thanks to @hstanev for the patch.

1.0.2

  • #56: Fix bug where order is wrong after adding objects. That had to do with using the count of the m2m objects for the next sort_value value. We now use the corret Max aggregation to make sure that newly added objects will be in order. Thanks to Scott Kyle for the report and patch.

1.0.1

  • Performance fix for sorted m2m admin widget. See #54 for details. Thanks to Jonathan Liuti for fixing this.

1.0.0

  • Hooray, we officially declare django-sortedm2m to be stable and promise to be backwards compatible to new releases (we already doing good since since the beginning in that regard).

  • Django 1.8 support for AlterSortedManyToManyField operation. Thanks to Nicolas Trésegnie for starting the implementation.

0.10.0

  • The creation of the sortedm2m intermediate model and database table is now fully done inside of the SortedManyToManyField class. That makes it much easier to modify the creation of this when creating a custom subclass of this field. See #49 for an example usecase.

  • Adding support for the custom field arguments like sorted and sort_value_field_name in Django 1.7 migrations. Thanks to Christian Kohlstedde for the patch.

0.9.5

  • Fixing setup.py when run on a system that does not use UTF-8 as default encoding. See #48 for details. Thanks to Richard Mitchell for the patch.

0.9.4

  • Fix: SortedMultipleChoiceField did not properly report changes of the data to Form.changed_data. Thanks to @smcoll for the patch.

0.9.3

  • Fix: AlterSortedManyToManyField operation failed for postgres databases.

  • Testing against MySQL databases.

0.9.2

  • Fix: AlterSortedManyToManyField operation failed for many to many fields which already contained some data.

0.9.1

  • Fix: When using the sortable admin widget, deselecting an item in the list had not effect. Thank you to madEng84 for the report and patch!

0.9.0

  • Adding AlterSortedManyToManyField migration operation that allows you to migrate from ManyToManyField to SortedManyToManyField and vice versa. Thanks to Joaquín Pérez for the patch!

  • Fix: Supporting migrations in Django 1.7.4.

  • Fix: The admin widget is not broken anymore for dynamically added inline forms. Thanks to Rubén Díaz for the patch!

0.8.1

  • Adding support for Django 1.7 migrations. Thanks to Patryk Hes and Richard Barran for their reports.

  • Adding czech translations. Thanks to @cuchac for the pull request.

0.8.0

  • Adding support for Django 1.7 and dropping support for Django 1.4.

0.7.0

  • Adding support for prefetch_related(). Thanks to Marcin Ossowski for the idea and patch.

0.6.1

  • Correct escaping of for attribute in label for the sortedm2m widget. Thanks to Mystic-Mirage for the report and fix.

0.6.0

  • Python 3 support!

  • Better widget. Thanks to Mike Knoop for the initial patch.

0.5.0

  • Django 1.5 support. Thanks to Antti Kaihola for the patches.

  • Dropping Django 1.3 support. Please use django-sortedm2m<0.5 if you need to use Django 1.3.

  • Adding support for a sort_value_field_name argument in SortedManyToManyField. Thanks to Trey Hunner for the idea.

0.4.0

  • Django 1.4 support. Thanks to Flavio Curella for the patch.

  • south support is only enabled if south is actually in your INSTALLED_APPS setting. Thanks to tcmb for the report and Florian Ilgenfritz for the patch.

0.3.3

  • South support (via monkeypatching, but anyway… it’s there!). Thanks to Chris Church for the patch. South migrations won’t pick up a changed sorted argument though.

0.3.2

  • Use already included jQuery version in global scope and don’t override with django’s version. Thank you to Hendrik van der Linde for reporting this issue.

0.3.1

  • Fixed packaging error.

0.3.0

  • Heavy internal refactorings. These were necessary to solve a problem with SortedManyToManyField and a reference to 'self'.

0.2.5

  • Forgot to exclude debug print/console.log statements from code. Sorry.

0.2.4

  • Fixing problems with SortedCheckboxSelectMultiple widget, especially in admin where a “create and add another item” popup is available.

0.2.3

  • Fixing issue with primary keys instead of model instances for .add() and .remove() methods in SortedRelatedManager.

0.2.2

  • Fixing validation error for SortedCheckboxSelectMultiple. It caused errors if only one value was passed.

0.2.1

  • Removed unnecessary reference of jquery ui css file in SortedCheckboxSelectMultiple. Thanks to Klaas van Schelven and Yuwei Yu for the hint.

0.2.0

  • Added a widget for use in admin.

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-sortedm2m-1.3.1.tar.gz (36.1 kB view details)

Uploaded Source

File details

Details for the file django-sortedm2m-1.3.1.tar.gz.

File metadata

File hashes

Hashes for django-sortedm2m-1.3.1.tar.gz
Algorithm Hash digest
SHA256 b7c9525b444fa891f094a27b356ffb3ddebdf65522e026a3ba25ac50bf6324d6
MD5 8b683392a37b6620c9f84c8989f08504
BLAKE2b-256 196b0bb7e53584baaa3e784fbf367fc061b302f76450aa87b3fa91a75f9dfeb6

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