如何创建一个管理系统可以排序的unicode字段?

2024-06-28 15:06:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Django来管理一个小的病人名单。在管理界面中,我有一些列是在管理员py文件。在

class InpatientAdmin(admin.ModelAdmin):
list_filter = ['discharged','date_of_admission']
date_hierarchy = 'date_of_admission'
list_display = ('room', '__unicode__', 'date_of_admission', 'date_of_discharge', 'discharged')
inlines = [ EncounterInline ]

unicode字段在模型中定义为

^{pr2}$

管理界面工作。Django程序员做的非常巧妙的事情。但是,当我单击unicode定义字段的标题时,它不会排序。我可以对房间、入院日期和出院日期进行排序,但unicode字段无法排序。我试着回来本人姓氏在unicode定义中,但这也不起作用。我怀疑unicode字段没有提供到比较例程的挂钩。在

我相信有一些简单的东西可以让这个工作,但我不知道谷歌用来找到解决方案的条件。感谢帮助。在

谢谢, 史蒂夫


Tags: 文件ofdjangopydate界面定义排序
2条回答

试图使用彼得·德格洛珀的答案,但有几个问题,这个片段应该放进去模型.py,但模型中没有定义self。在

因此

self.__unicode__.admin_order_field = 'last_name'

不会有用的。在

即使你尝试:

^{pr2}$

管理员很固执,不想分类。因此,我找到了this solution。即创建一个模型方法,该方法只返回unicode名称,然后定义排序字段。在

同样,不是我的解决方案(代码来自链接),但它应该帮助面临相同问题的其他人:

模型.py

def unicode_sort(self):
    return self.__unicode__()

unicode_sort.admin_order_field = 'sort'
unicode_sort.short_description = u'name'

管理员py

list_display = ('unicode_sort',) 

如果希望按单个字段排序(比如,last_name),可以将其设置为__unicode__方法的admin_order_field。不支持按可调用字段进行更复杂的排序。在

https://docs.djangoproject.com/en/dev/ref/contrib/admin/

Usually, elements of list_display that aren’t actual database fields can’t be used in sorting (because Django does all the sorting at the database level).

However, if an element of list_display represents a certain database field, you can indicate this fact by setting the admin_order_field attribute of the item.

因此,只要逻辑符合您的要求,这应该是可行的:

def __unicode__(self):
    return '%s, %s %s' % (self.last_name, self.first_name, self.DOB)
self.__unicode__.admin_order_field = 'last_name'

相关问题 更多 >