Package: django-sortedm2m
sortedm2mis a drop-in replacement for django’s ownManyToManyField.
The providedSortedManyToManyFieldbehaves like the original one but
remembers the order of added relations.Use CasesImagine 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 theSortedManyToManyFieldprovided by this package as drop in replacement for django’sManyToManyField.Requirementsdjango-sortedm2mruns on Python 3.6+ and Django from 2.1 to 3.0.UsageUseSortedManyToManyFieldlikeManyToManyFieldin 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)SortedManyToManyFieldYou can use the following arguments to modify the default behavior:sortedDefault:TrueYou can set thesortedtoFalsewhich will force theSortedManyToManyFieldin behaving like Django’s originalManyToManyField. No ordering will be performed on relation nor will the
intermediate table have a database field for storing ordering information.sort_value_field_nameDefault:'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.base_classDefault:NoneYou can set thebase_class, which is the base class of the through model of
the sortedm2m relationship between models to an abstract base class containing
a__str__method to improve the string representations of sortedm2m
relationships.NoteYou also could use it to add additional fields to the through model. But
please beware: These fields will not be created or modified by an
automatically created migration. You will need to take care of migrations
yourself. In most cases when you want to add another field, considernotusing sortedm2m but use a ordinary Django ManyToManyField and
specifyyour own through model.Migrating aManyToManyFieldto be aSortedManyToManyFieldIf you are using Django’s migration framework and want to change aManyToManyFieldto be aSortedManyToManyField(or the other way
around), you will find that a migration created by Django’smakemigrationswill not work as expected.In order to migrate aManyToManyFieldto aSortedManyToManyField, you
change the field in your models to be aSortedManyToManyFieldas
appropriate and create a new migration withmanage.py makemigrations.
Before applying it, edit the migration file and change in theoperationslistmigrations.AlterFieldtoAlterSortedManyToManyField(import it
fromsortedm2m.operations).  This operation will take care of changing the
intermediate tables, add the ordering field and fill in default values.AdminSortedManyToManyFieldprovides 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 addsortedm2mto 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 surenotto have the model listed in anyfilter_horizontalorfilter_verticaltuples inside of yourModelAdmindefinitions.If you did it right, you’ll wind up with something like this:It’s also possible to use theSortedManyToManyFieldwith admin’sraw_id_fieldsoption in theModelAdmindefinition. Add the name of theSortedManyToManyFieldto 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',)ContributeThis is aJazzbandproject. By contributing you agree to abide by theContributor Code of Conductand follow theguidelines.You can find the latest development version onGithub. Get there and fork it, file bugs or send well wishes.Running the testsI recommend to usetoxto run the tests for all relevant python versions
all at once. Therefore installtoxwithpip install tox, then type in
the root directory of thedjango-sortedm2mcheckout:toxThe tests are run against SQLite, then against PostgreSQL, then against mySQL -
so you need to install PostgreSQL and mySQL on your dev environment, and should
have a role/usersortedm2mset up for both PostgreSQL and mySQL.Code QualityThis project usesisort,pycodestyle,
andpylintto manage validate code quality. These validations can be run with the
following command:tox -e qualityChangelog3.1.1#191: Fixed JS bug for popup in Django admin3.1.0#178: Bug fixes#178: Fixed Pylint error#175: Fixed jQuery UI error#183: Migrated to GitHub Actions for CI#184: Added support for Django 3.23.0.2#168: Restoredadmin/js/jquery.init.js3.0.1#164: Added all locales to distributable#162: Added missing files to MANIFEST.in, and removed .DS_Store files#150: Added German and Spanish translations#149: Removedadmin/js/jquery.init.jsfromSortedCheckboxSelectMultiple3.0.0#147: Dropped support for Django 2.0#152: Dropped support for Django 1.10#152: Add support for Python 3.8#152: Add support for Django 3.02.0.0#135: Updated README with Jazzband details, and added CONTRIBUTING.md#136: Dropped support for Python 2.6 and 3.3, and Django < 1.11#130: Added support for Python 3.7 and Django 2.0 to 2.2#130: Add support of custom through models (only for Django >= 2.2)#138: Added coverage reporting1.5.0#101: Add support for a custom base class for the many to many intermediate
class. See the README for documentation. Thank you Rohith Asrk for the patch.#87: FixAlterSortedManyToManyFieldoperation to support custom set_sort_field_name.1.4.0#104: Add compatibility for Django 1.10 and 1.11!
Thank you Frankie Dintino for the patch.#94: Add french translation files. Mainly for strings in the admin.
Thanks to ppython for the patch.#93: Prevent users from accidentally importing and usingManyToManyFieldinstead ofSortedManyToManyFieldfromsortedm2m.
Thanks Dayne May for the patch.1.3.3#91&#92: Fix admin widget, when used with Django 1.10. The add a new
item opup was not closing. Thanks to Tipuch for the patch.1.3.2#80&#83: FixSortedMultipleChoiceField.cleanif the validated
value isNone. Thanks to Alex Mannhold for the patch.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-itemselector in the widget’s JavaScript code to
target the list items. This was previouslyul.sortedm2m li. This improves
compatibility other markup that does not want to useul/litags. 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 thesortedm2m-itemclass 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.1skipped1.2.0Dropping 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 inSortedCheckboxSelectMultiple. 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 theallow_migrate_modelmethod).
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 thecountof the m2m objects for the nextsort_valuevalue. We now use the corretMaxaggregation to make sure that newly
added objects will be in order. Thanks to Scott Kyle for the report and
patch.1.0.1Performance fix for sorted m2m admin widget. See#54for details. Thanks
to Jonathan Liuti for fixing this.1.0.0Hooray, we officially declaredjango-sortedm2mto 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 forAlterSortedManyToManyFieldoperation. Thanks to
Nicolas Trésegnie for starting the implementation.0.10.0The creation of the sortedm2m intermediate model and database table is now
fully done inside of theSortedManyToManyFieldclass. That makes it much
easier to modify the creation of this when creating a custom subclass of this
field. See#49for an example usecase.Adding support for the custom field arguments likesortedandsort_value_field_namein Django 1.7 migrations. Thanks to Christian
Kohlstedde for the patch.0.9.5Fixingsetup.pywhen run on a system that does not use UTF-8 as default
encoding. See#48for details. Thanks to Richard Mitchell for the patch.0.9.4Fix:SortedMultipleChoiceFielddid not properly report changes of the
data toForm.changed_data. Thanks to @smcoll for the patch.0.9.3Fix:AlterSortedManyToManyFieldoperation failed for postgres databases.Testing against MySQL databases.0.9.2Fix:AlterSortedManyToManyFieldoperation failed for many to many fields
which already contained some data.0.9.1Fix: 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.0AddingAlterSortedManyToManyFieldmigration operation that allows you to
migrate fromManyToManyFieldtoSortedManyToManyFieldand 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.1Adding 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.0Adding support for Django 1.7 and dropping support for Django 1.4.0.7.0Adding support forprefetch_related(). Thanks to Marcin Ossowski for
the idea and patch.0.6.1Correct escaping offorattribute in label for the sortedm2m widget. Thanks
to Mystic-Mirage for the report and fix.0.6.0Python 3 support!Better widget. Thanks to Mike Knoop for the initial patch.0.5.0Django 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 asort_value_field_nameargument inSortedManyToManyField. Thanks to Trey Hunner for the idea.0.4.0Django 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.3South support (via monkeypatching, but anyway… it’s there!). Thanks to
Chris Church for the patch. South migrations won’t pick up a changedsortedargument though.0.3.2Use 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.1Fixed packaging error.0.3.0Heavy internal refactorings. These were necessary to solve a problem withSortedManyToManyFieldand a reference to'self'.0.2.5Forgot to exclude debug print/console.log statements from code. Sorry.0.2.4Fixing problems withSortedCheckboxSelectMultiplewidget, especially in
admin where a “create and add another item” popup is available.0.2.3Fixing issue with primary keys instead of model instances for.add()and.remove()methods inSortedRelatedManager.0.2.2Fixing validation error forSortedCheckboxSelectMultiple. It caused
errors if only one value was passed.0.2.1Removed unnecessary reference of jquery ui css file inSortedCheckboxSelectMultiple. Thanks to Klaas van Schelven and Yuwei Yu
for the hint.0.2.0Added a widget for use in admin.