Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 417
segaco Avatar asked May 19 '11 17:05

segaco


People also ask

What does ForeignKey mean in Django?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.

How does Django define many-to-one relationships?

For example, a Menu model record can have many Item model records associated with it and yet an Item belongs to a single Menu record. To define a one to many relationship in Django models you use the ForeignKey data type on the model that has the many records (e.g. on the Item model).

What is the difference between ForeignKey and OneToOneField?

The only difference between these two is that ForeignKey field consists of on_delete option along with a model's class because it's used for many-to-one relationships while on the other hand, the OneToOneField, only carries out a one-to-one relationship and requires only the model's class.


1 Answers

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.

like image 55
Cyril N. Avatar answered Sep 20 '22 13:09

Cyril N.