[Django]-Ordering Choices in ModelForm ManytoManyField DJANGO

76👍

There are several ways:

You can override the queryset ordering on a per-form basis, set the ordering meta class option, or override the model manager queryset with an ordering method.

Override global model manager queryset

class IndustryManager(models.Manager):
    def get_query_set(self):
        return (
            super(IndustryManager, self)
            .get_query_set()
            .order_by('name')
        )

class Industry(models.Model):
    name = models.CharField(max_length=128)
    objects = IndustryManager()

Specify global meta option ordering

class Industry(models.Model):
    name = models.CharField(max_length=128)

    class Meta:
        ordering = ['name']

Per form ordering

class MyForm(forms.ModelForm):
    class Meta:
        model = Business

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)   
        self.fields['industry'].queryset = Industry.objects.order_by('name')

There’s also a shortcut called formfield_for_manytomany if you are dealing with the django admin.

1👍

I like this method:

class BusinessForm(forms.ModelForm):

    class Meta:
        model = Business

    industry = forms.ModelMultipleChoiceField(
               queryset=Industry.objects.order_by('name'))

I like it, since it does not alter the database model, and since it is declarative (less programming).

Leave a comment