Django admin:list_display 中的二级排序
在 Django 管理员的 list_display 中显示模型时,我想首先按一列排序,然后按另一列排序。
这是一个示例模型:
class Customer(models.Model):
name = models.CharField(max_length=30)
the_date = models.DateField()
如何实现这一点?
While showing a model in Django's admin's list_display, I'd like to sort first by one column, then by another.
Here's an example model:
class Customer(models.Model):
name = models.CharField(max_length=30)
the_date = models.DateField()
How could this be achieved?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您正在寻找管理类的“排序”属性。
http://docs.djangoproject.com/en/1.3/ref/contrib/ admin/
编辑:我之前的答案是不正确的。根据上面的文档,Django 仅尊重元组中的第一个条目。有/曾经有一张票来解决这个问题,但没有任何结果。我还尝试了各种其他建议的解决方案,但它们似乎都不适合我的 Django 版本。
然而,今天我作为项目的一部分回到了这个问题,并终于找到了对我有用的东西。我的解决方案基于此 Django 代码片段,为了完整起见,我将在此处发布代码片段。
I think you are looking for the "ordering" attribute of an admin class.
http://docs.djangoproject.com/en/1.3/ref/contrib/admin/
Edit: My previous answer is incorrect. According to the documentation above, Django only honors the first entry in the tuple. There is/was a ticket to resolve this that went nowhere. There are various other proposed solutions that I also tried, but none of them seemed to work with my version of Django.
However, I came back to this problem today as part of a project and finally found something that worked for me. My solution was based upon this Django snippet, and I will post the snippet code here for completeness.
这是基于 bogeyman 4 月 1 日编辑的答案,但细分为基本功能。
在我的 models.py 中,像往常一样在模型
Meta
中定义ordering
:然后在 admin.py 子类
ChangeList
中,但强制 query_set 最终成为按模型元中指定的顺序排序。如果您想在 ModelAdmin 中定义顺序;你也可以这样做;只需将
return queryset.order_by(*self.model._meta.ordering)
更改为return queryset.order_by(*self.model_admin.ordering)
并添加定义的列表
。CustomerAdmin
中的 >ordering = ['the_date', 'name']This is based on bogeyman Apr 1 edited answer, but broken down to the essential feature.
In my models.py define
ordering
in the modelsMeta
as usual:Then in admin.py subclass
ChangeList
, but force the query_set to ultimately be sorted by the ordering specified in the Meta of the model.If you'd rather define the ordering in the ModelAdmin; you could do that as well; just change
return queryset.order_by(*self.model._meta.ordering)
toreturn queryset.order_by(*self.model_admin.ordering)
and add a list definingordering = ['the_date', 'name']
inCustomerAdmin
.您可以通过使用 Django trunk 而不是 1.3
https://docs.djangoproject 来实现此目的.com/en/dev/ref/contrib/admin/
You can achieve this by using Django trunk rather than 1.3
https://docs.djangoproject.com/en/dev/ref/contrib/admin/