对所有过滤对象的 django 管理操作
管理操作可以对列表页面中选定的对象进行操作。 是否可以对所有过滤后的对象进行操作?
例如,如果管理员搜索以“T 恤”开头的产品名称,结果会显示 400 种产品,并且希望将所有产品的价格提高 10%。 如果管理员一次只能修改一页结果,那将花费很大的精力。
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
自定义操作应该用于一组选定的对象,因此我认为没有标准的方法可以完成您想要的操作。
但我想我有一个可能对你有用的黑客......(意思是:使用你自己的风险并且未经测试)
在你的操作函数中,
request.GET
将包含在中使用的 q 参数管理员搜索。因此,如果您在搜索中输入“T-Shirt”,您应该会看到request.GET
如下所示:您可以完全忽略自定义操作函数接收的查询字符串参数,并根据
request.GET
的 sq 参数构建您自己的查询集。比如:我会确保禁止任何 q 为空的请求。在您阅读
name__contains
的地方,您应该模仿您为产品对象的管理创建的任何过滤器(因此,如果搜索仅查看名称字段,name__contains
可能会就足够了;如果它查看名称和描述,您在操作函数中也会有一个更复杂的过滤器)。也许我还会添加一个中间页面,说明哪些模型将受到影响,并让用户单击“我真的知道我在做什么”确认按钮。查看 django.contrib.admin.actions 的代码,了解如何列出正在删除的对象的示例。它应该为您指明正确的方向。
注意:用户仍然必须在管理页面中选择某些内容,否则永远不会调用操作函数。
The custom actions are supposed to be used on a group of selected objects, so I don't think there is a standard way of doing what you want.
But I think I have a hack that might work for you... (meaning: use at your own risk and it is untested)
In your action function the
request.GET
will contain the q parameter used in the admin search. So if you type "T-Shirt" in the search, you should seerequest.GET
look something like:<QueryDict: {u'q': [u'T-Shirt']}>
You could completely disregard the querystring parameter that your custom action function receives and build your own queryset based on that
request.GET
's q parameter. Something like:I would make sure to forbid any requests where q is empty. And where you read
name__contains
you should be mimicking whatever filter you created for the admin of your product object (so, if the search is only looking at the name field,name__contains
might suffice; if it looks at the name and description, you would have a more complex filter here in the action function too).I would also, maybe, add an intermediate page stating what models will be affected and have the user click on "I really know what I'm doing" confirmation button. Look at the code for
django.contrib.admin.actions
for an example of how to list what objects are being deleted. It should point you in the right direction.NOTE: the users would still have to select something in the admin page, otherwise the action function would never get called.
这是一个更通用的解决方案,尚未经过充分测试(而且非常幼稚),因此它可能会因奇怪的过滤器而崩溃。对我来说,可以使用日期过滤器、外键过滤器、布尔过滤器。
This is a more generic solution, is not fully tested(and its pretty naive), so it might break with strange filters. For me works with date filters, foreign key filters, boolean filters.