Django admin get_FOO_display

◇◆丶佛笑我妖孽 提交于 2020-01-02 09:52:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!