Django 管理默认过滤器
我知道我已经设法做到了这一点,但不记得如何做到这一点,也找不到任何有关此的文档。.
如何在管理中的对象列表视图上默认应用过滤器?
我有一个列出报价的应用程序,这些报价有一个状态(例如:接受、拒绝、保留......)。
我希望默认情况下将过滤器设置为 status='accepted' ,即..
I know I already managed to do this but can't remember how nor I can't find any documentation about this..
How can apply a filter by default on a object list view in the admin ?
I have an app which list quotes and those quotes have a status (ex: accepted, rejected, on hold ..).
I want the filter set on status='accepted' by default that is..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
更可重用的方法:
然后只需在 ModelAdmin 上定义一个 default_filters :
A bit more reusable approach:
And then just define a default_filters on your ModelAdmin:
最后,这就是我正在寻找的:
另一种方式,使用管理类中的 queryset 方法不起作用。事实上,它确实过滤了结果,但它使过滤功能被破坏。
我找到的解决方案也不完美,当使用它来选择“全部/过滤器”时,这是不可能的。就我而言,它并不引人注目,但已经足够好了..
Finally, this is what I was looking for:
The other way, with the queryset method in the admin class does not work. In fact it does filter the results, but it leaves the filter functionality broken.
The solution I've found is not perfect either, it's not possible when using it to select the "All/ filter. In my case it's not dramatic and it will be good enough though..
您可以覆盖查询集
,但是通过覆盖查询集,您将永远无法查看状态不为“已接受”的报价。
或者,您可以链接到以下 URL,将过滤器添加到 GET 参数。
You can override the queryset
However by overriding the queryset you won't ever be able to view quotes that do not have status "accepted".
Alternatively, you can link to the following URL, adding the filter to the GET parameters.
简短而干净的解决方案。单击更改列表视图时,与“全部”选项配合良好。
Short and clean solution. Works nice with "All" option when clicked on change list view.
我通过支持“全部”解决了这个问题。
在 models.py 中:
在 admin.py 中:
I solved this problem with support 'all'.
in models.py:
in admin.py:
我想我已经找到了一种在不限制用户的情况下做到这一点的方法。只需查看引荐来源网址即可确定用户是否刚刚到达此页面。如果是这样,根据该过滤器将它们重定向到您想要的默认 URL。
I think I've found a way to do this without limiting the user. Just look at the referer to determine if the user just arrived at this page. If so redirect them to the default url you want based on that filter.
这对我有用,避免了 h3 提到的“全部”问题。
This worked for me and avoided having the "All" problem mentioned by h3.
这是我对 glic3rinu 代码的更新(请参阅那里的评论),它适用于 Python 3.4 和 Django 1.9.7:
Here is my update for glic3rinu's code (see comment there), which works on Python 3.4 and Django 1.9.7:
这是我在 admin 中设置默认过滤器的尝试(仅使用 Django 1.11 进行了测试):
技巧是检查 self.value() is None 以获得默认行为
Here is my attempt to have a default filter set in admin (only tested with Django 1.11):
The trick is to check
self.value() is None
to get the default behaviour