Answer a question

Here's a (very) simplified version of my models:

laboratory/models.py

class Lab(Model):
    professor = ForeignKey('authors.Author')

authors/models.py

class Author(Model):
    name = CharField(max_length=100)

In the Django admin, when I add or update a Lab, a drop-down list containing each professors is automatically generated and displayed. The problem is this list is very long and it is not alphabetically ordered. I want the professor drop-down list to be alphabetically ordered by "name" field.

How can I do that?

Answers

You can define default ordering for Author model:

class Author(Model):
    name = CharField(max_length=100)

    class Meta:
        ordering = ('name',)

Keep in mind that this causes the objects in Django also to ordered and migration will have to be done.

You can do ordering = ['name'] under the AuthorAdmin file to order only for admin dashboard.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐