Django管理员get_FOO_display [英] Django admin get_FOO_display
问题描述
我有这样的模型:
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', )
但是我在状态列中看到字段名称 curried 。
But I see field name curried in status column.
如何为列指定普通名称 Status 还是我做错了什么?
How I can give normal name Status to column or I make something wrong?
我可以按此字段排序吗?
And can I sort by this field?
推荐答案
设置可调用的 get_status_display
的 short_description
属性,以控制列名。您无法按计算值排序(Django使用数据库进行排序),但是如果基础 status
字段给出了正确的排序顺序,请设置
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'
.
'状态'
的admin_order_field 属性。 > list_display 给出了设置两个属性的示例:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
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
由于它是一种自动创建的方法,因此稍微复杂一些-在类定义时该callable不可用。我认为,您可以在注册管理员之前进行设置,但我尚未进行测试:
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)
如果这不起作用,请在恰好调用选择字段的 contribute_to_class
方法时追逐-created方法是弄清楚何时可以设置这些属性的一种方法。但是我可能会跳过它,并在管理类上贴上一个包装,我知道可以在其中设置属性。
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.
这篇关于Django管理员get_FOO_display的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!