[Django]-How to order the results of a ForeignKey relationship in a Django form?

26👍

You can use the ordering property:

class Country(models.Model):
    name = models.CharField(max_length=80)

    class Meta:
        ordering = ["name"]

If you set the ordering to the Country class, it shall display them as you want.

12👍

If you can’t or don’t want to use the ordering attribute in class Meta of model, you also can do this:

You need make a Form object, something like:

from django import forms
class PersonForm(forms.ModelForm):
    country = forms.ModelChoiceField(queryset=Country.objects.all().order_by('name'))
    class Meta:
        model = Person

field types for formsmodels

11👍

There’s 2 good answers here, but I wanted to retain help_text, blank, and other settings from the model without having to repeat them and also not change the default ordering on the model. Here’s what I did:

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person

    def __init__(self, *args, **kwargs):
        super(PersonForm, self).__init__(*args, **kwargs)
        self.fields['country'].queryset = self.fields['country'].queryset.order_by('name')

Essentially I just updated the queryset on the automatically added field to order the way I wanted.

1👍

try adding this into class Meta, inside class Person:

ordering = ['country']

http://docs.djangoproject.com/en/dev/ref/models/options/#ordering

0👍

In view.py
First: you create the form

form = YourForm(request.POST)

Later your set the query:

form.fields['country '].queryset = YourDBTable.objects.all().order_by('Your_Attr')

Leave a comment