8

From the django tutorial

 was_published_recently.admin_order_field = 'pub_date'

What is this statement really doing?

Vijay Chavda
  • 826
  • 2
  • 15
  • 34
BluePython
  • 1,635
  • 3
  • 24
  • 35

1 Answers1

12

This is in reference to the admin section of django.

In the admin section corresponding to models, each models has a property called list_display, which control which fields are displayed on the change list (list display of all the objects) page of the admin.

Now, if you wish to change the default sort order for was_published_recently in the list_display you can do so by setting the admin_order_field attribute.

So, in the example:

class Poll(models.Model):
    # ...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

You are adding a custom column called was_published_recently and specifying the sort order to be the database field pub_date when the "sort" option for the column was_published_recently is clicked.

You can understand this better by scrolling down to the information pertaining to admin_order_field in this link

karthikr
  • 97,368
  • 26
  • 197
  • 188
  • 1
    This answer is almost perfect, but the code you quoted is not what creates the custom column for `was_published_recently`. The code that does is in `polls/admin.py` under the class `PollAdmin`. It's the line: `list_display = ('question', 'pub_date', 'was_published_recently')`. The code you showed (from `poll/models.py`) modifies the default state of that column. – liquidki Aug 16 '14 at 22:19