Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering Choices in ModelForm ManytoManyField DJANGO

I have in my models.py

class Business(models.Model):
   industry = models.models.ManyToManyField(Industry)

in forms.py

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

When I render the form, the industry names appear in a multiple select box. What do I do to make the industry names in alphabetical order?

like image 573
Eva611 Avatar asked Jun 30 '11 21:06

Eva611


2 Answers

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.

like image 187
Yuji 'Tomita' Tomita Avatar answered Nov 14 '22 20:11

Yuji 'Tomita' Tomita


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).

like image 28
guettli Avatar answered Nov 14 '22 20:11

guettli