问题
I have model like this:
class M(models.Model):
CHOICES = (('A', 'Accepted'), ('R', 'Rejected'))
status = model.CharField(max_length=1, choices=CHOICES)
I register this model in admin by this way:
class MAdmin(admin.ModelAdmin):
list_display = ('get_status_display', )
But I see field name curried in status column.
How I can give normal name Status to column or I make something wrong?
And can I sort by this field?
回答1:
Set the short_description attribute of your get_status_display callable to control the column name. You cannot sort by a calculated value (Django uses the database to do the sorting) but if your underlying status field gives the correct sort order, set the admin_order_field attribute to 'status'.
The docs for list_display give examples of setting both attributes:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
Since it's an auto-created method, it's marginally more complicated - the callable isn't available at class definition time. I think you can set them before registering the admin, but I haven't tested that:
M.get_status_display.short_description = 'status'
M.get_status_display.admin_order_field = 'status'
admin.site.register(M, MAdmin)
If that doesn't work, chasing down when exactly the choice field's contribute_to_class method gets called to add the auto-created method is one way to figure out when you can set those attributes. But I'd probably just skip it and stick a wrapper on the admin class, where I know I can set the attributes.
回答2:
Add these attributes to your function
def get_status_display(self, obj):
--
YOUR CODE HERE
--
get_status_display.short_description = 'status'
get_status_display.admin_order_field = 'status'
来源:https://stackoverflow.com/questions/21242486/django-admin-get-foo-display