1.6 Tutorial: Alternative code position for Django admin list display settings

145 views
Skip to first unread message

Xiao Jia

unread,
Nov 21, 2013, 6:22:29 AM11/21/13
to django...@googlegroups.com

I am following the tutorial of Django 1.6, which includes a model Poll that has a derived attributewas_published_recently (a method of class Poll). The model was originally defined as follows.

# polls/models.py (excerpted)

class Poll(models.Model):
    # ...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

And the admin interface for this app:

# polls/admin.py (excerpted)

class PollAdmin(admin.ModelAdmin):
    # ...
    list_display = ('question', 'pub_date', 'was_published_recently')

admin.site.register(Poll, PollAdmin)

Now we want to improve the display and sorting functionality of was_published_recently.

In the tutorial, file polls/models.py is updated:

class Poll(models.Model):
    # ...
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

However, I think this may not be good enough in practice, because what we are specifying is completely about the admin user interface, not the model per se. So I instead updated polls/admin.py:

class PollAdmin(admin.ModelAdmin):
    Poll.was_published_recently.admin_order_field = 'pub_date'
    Poll.was_published_recently.boolean = True
    Poll.was_published_recently.short_description = 'Published recently?'
    # ...

After this modification, the app works as expected as well (multiple polls work well also). Since I am new to Python, I investigated a bit further by printing was_published_recently in both Poll andPollAdmin:

class Poll(models.Model):
    # ...
    print("in class Poll", was_published_recently)

class PollAdmin(admin.ModelAdmin):
    print("in class PollAdmin", Poll.was_published_recently)
    # ...

And the output is

in class Poll <function Poll.was_published_recently at 0x10fc92050>
in class PollAdmin <function Poll.was_published_recently at 0x10fc92050>

So apparently was_published_recently in class Poll is the same asPoll.published_recently accessed in class PollAdmin.

My question: Should I specify the admin_order_field stuffs in admin.py or models.py? If specified in admin.py instead of models.py, are there any drawbacks?

tim

unread,
Nov 21, 2013, 10:29:43 AM11/21/13
to django...@googlegroups.com
It should work as documented. I would not use the alternative of modifying the model in other files that you described.
Reply all
Reply to author
Forward
0 new messages