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?
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.
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).
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With