• Stars
    star
    511
  • Rank 86,473 (Top 2 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created about 14 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A transparent sorted ManyToMany field for django.

django-sortedm2m

Jazzband PyPI Release Build Status Code coverage

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.

Use Cases

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 3.6+ and multiple Django versions. See the .github/workflows/test.yml configuration for the tested Django versions.

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.

base_class

Default: None

You can set the base_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.

Note

You 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, consider not using sortedm2m but use a ordinary Django ManyToManyField and specify your own through model.

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

This is a Jazzband project. By contributing you agree to abide by the Contributor Code of Conduct and follow the guidelines.

You can find the latest development version on Github. Get there and fork it, file bugs or send well 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

The 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/user sortedm2m set up for both PostgreSQL and mySQL.

Code Quality

This project uses isort, pycodestyle, and pylint to manage validate code quality. These validations can be run with the following command:

tox -e quality

More Repositories

1

django-debug-toolbar

A configurable set of panels that display various debug information about the current request/response.
Python
8,023
star
2

pip-tools

A set of tools to keep your pinned Python dependencies fresh.
Python
7,668
star
3

tablib

Python Module for Tabular Datasets in XLS, CSV, JSON, YAML, &c.
Python
4,586
star
4

django-silk

Silky smooth profiling for Django
Python
4,380
star
5

djangorestframework-simplejwt

A JSON Web Token authentication plugin for the Django REST Framework.
Python
3,957
star
6

django-taggit

Simple tagging for django
Python
3,307
star
7

django-oauth-toolkit

OAuth2 goodies for the Djangonauts!
Python
3,148
star
8

django-redis

Full featured redis cache backend for Django.
Python
2,860
star
9

django-model-utils

Django model mixins and utilities.
Python
2,638
star
10

Watson

⌚ A wonderful CLI to track your time!
Python
2,450
star
11

django-push-notifications

Send push notifications to mobile devices through GCM or APNS in Django.
Python
2,275
star
12

django-simple-history

Store model history and view/revert changes from admin site.
Python
2,189
star
13

django-widget-tweaks

Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.
Python
2,077
star
14

sorl-thumbnail

Thumbnails for Django
Python
1,743
star
15

django-constance

Dynamic Django settings.
Python
1,687
star
16

django-two-factor-auth

Complete Two-Factor Authentication for Django providing the easiest integration into most Django projects.
Python
1,679
star
17

django-polymorphic

Improved Django model inheritance with automatic downcasting
Python
1,648
star
18

django-pipeline

Pipeline is an asset packaging library for Django.
Python
1,508
star
19

dj-database-url

Use Database URLs in your Django Application.
Python
1,471
star
20

django-axes

Keep track of failed login attempts in Django-powered sites.
Python
1,463
star
21

prettytable

Display tabular data in a visually appealing ASCII table format
Python
1,336
star
22

django-tinymce

TinyMCE integration for Django
JavaScript
1,270
star
23

django-analytical

Analytics services for Django projects
Python
1,197
star
24

django-admin2

Extendable, adaptable rewrite of django.contrib.admin
Python
1,185
star
25

django-rest-knox

Authentication Module for django rest auth
Python
1,130
star
26

django-waffle

A feature flipper for Django
Python
1,128
star
27

django-smart-selects

chained and grouped selects for django forms
Python
1,125
star
28

django-auditlog

A Django app that keeps a log of changes made to an object.
Python
1,108
star
29

django-configurations

A helper for organizing Django project settings by relying on well established programming patterns.
Python
1,085
star
30

django-defender

A simple super fast django reusable app that blocks people from brute forcing login attempts
Python
1,035
star
31

django-payments

Universal payment handling for Django.
Python
1,023
star
32

django-hosts

Dynamic and static host resolving for Django. Maps hostnames to URLconfs.
Python
977
star
33

django-dbbackup

Management commands to help backup and restore your project database and media files
Python
959
star
34

geojson

Python bindings and utilities for GeoJSON
Python
913
star
35

django-nose

Django test runner using nose
Python
882
star
36

django-newsletter

An email newsletter application for the Django web application framework, including an extended admin interface, web (un)subscription, dynamic e-mail templates, an archive and HTML email support.
Python
845
star
37

django-floppyforms

Full control of form rendering in the templates.
Python
841
star
38

django-avatar

A Django app for handling user avatars.
Python
806
star
39

django-formtools

A set of high-level abstractions for Django forms
Python
790
star
40

django-user-sessions

Extend Django sessions with a foreign key back to the user, allowing enumerating all user's sessions.
Python
616
star
41

django-admin-sortable

Generic drag-and-drop ordering for objects and tabular inlines in Django Admin
Python
564
star
42

django-invitations

Generic invitations app for Django
Python
557
star
43

django-recurrence

Utility for working with recurring dates in Django.
Python
475
star
44

django-categories

This app attempts to provide a generic category system that multiple apps could use. It uses MPTT for the tree storage and provides a custom admin for better visualization (copied and modified from feinCMS).
Python
458
star
45

django-robots

A Django app for managing robots.txt files following the robots exclusion protocol
Python
457
star
46

wagtailmenus

An app to help you manage and render menus in your Wagtail projects more effectively
Python
394
star
47

django-embed-video

Django app for easy embedding YouTube and Vimeo videos and music from SoundCloud.
Python
383
star
48

django-downloadview

Serve files with Django.
Python
378
star
49

django-eav2

Django EAV 2 - EAV storage for modern Django
Python
343
star
50

jsonmodels

jsonmodels is library to make it easier for you to deal with structures that are converted to, or read from JSON.
Python
335
star
51

django-queued-storage

Provides a proxy for Django storage backends that allows you to upload files locally and eventually serve them remotely
Python
316
star
52

django-permission

[Not maintained] An enhanced permission system which support object permission in Django
Python
302
star
53

django-revproxy

Reverse Proxy view that supports all HTTP methods, Diazo transformations and Single Sign-On.
Python
300
star
54

django-authority

A Django app that provides generic per-object-permissions for Django's auth app and helpers to create custom permission checks.
Python
292
star
55

django-simple-menu

Simple, yet powerful, code-based menus for Django applications
Python
264
star
56

django-dbtemplates

Django template loader for database stored templates with extensible cache backend
JavaScript
252
star
57

django-fsm-log

Automatic logging for Django FSM
Python
242
star
58

django-mongonaut

Built from scratch to replicate some of the Django admin functionality and add some more, to serve as an introspective interface for Django and Mongo.
Python
240
star
59

django-cookie-consent

Reusable application for managing various cookies and visitors consent for their use in Django project.
Python
224
star
60

django-celery-monitor

Celery Monitoring for Django
Python
197
star
61

docopt-ng

Humane command line arguments parser. Now with maintenance, typehints, and complete test coverage.
Python
178
star
62

django-ddp

Django/PostgreSQL implementation of the Meteor server.
Python
167
star
63

icalevents

Python module for iCal URL/file parsing and querying.
Python
156
star
64

django-voting

A generic voting application for Django
Python
99
star
65

django-ical

iCal feeds for Django based on Django's syndication feed framework.
Python
92
star
66

django-redshift-backend

Redshift database backend for Django
Python
83
star
67

django-flatblocks

django-chunks + headerfield + variable chunknames + "inclusion tag" == django-flatblocks
Python
82
star
68

pathlib2

Backport of pathlib aiming to support the full stdlib Python API.
Python
81
star
69

website

Code for the Jazzband website
Python
66
star
70

django-sorter

A helper app for sorting objects in Django templates.
Python
54
star
71

django-discover-jenkins

A streamlined fork of django-jenkins designed to work with the default test command and the discover runner
Python
49
star
72

django-fernet-encrypted-fields

Python
47
star
73

contextlib2

contextlib2 is a backport of the standard library's contextlib module to earlier Python versions.
Python
38
star
74

imaplib2

Fork of Piers Lauder's imaplib2 library for Python.
Python
33
star
75

help

Use this repo to get help from the roadies
27
star
76

django-postgres-utils

Django app providing additional lookups and functions for PostgreSQL
Python
9
star
77

.github

Community health and config files for Jazzband
7
star
78

admin

Some admin files for Jazzband
3
star
79

actions

Various GitHub actions for Jazzband projects
1
star