开发者

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

I have this models in Django

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

class Person(models.Model):
    first_name = models.CharField(max_length=100, db_index=True)
    last_name = models.CharField(max_length=100, db_index=True)
    country 开发者_运维问答= models.ForeignKey(Country)

and this ModelForm

class PersonForm(forms.ModelForm):

    class Meta:
        model = Person

when I use this form in a template, everything works fine, but the country list in the <select> appears disordered. How can I order it?


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.


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


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.


try adding this into class Meta, inside class Person:

ordering = ['country']

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


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')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜