在Django中重新订购对象的有效方法
我已经编写了一个查询,以根据我在API请求中获得的值重新订购对象。 以下是我编写的示例代码:
@action(detail=False, permission_classes=[], methods=["PUT"])
def reorder_modules(self, request, *args, **kwargs):
"""
ReOrdering Modules
Sample request data
{
<module_id>: <ordering_number>
12: 2,
13: 1,
14, 3,
}
"""
updatabale_modules = []
for module_id, module_order in request.data.get("modules", {}).items():
_mod = Module.objects.get(id=module_id)
_mod.order = module_order
updatabale_modules.append(_mod)
Module.objects.bulk_update(updatabale_modules, ["order"])
return Response({"detail": "successfully reordered course modules"}, status=HTTP_200_OK)
有什么方法可以避免循环和获取每个模块? 如果可能的话,我应该能够保存一些查询。
仅供参考,我正在使用MySQL数据库。
I have written a query to re-order objects based on the values I get in the API request.
Below is the sample code I have written:
@action(detail=False, permission_classes=[], methods=["PUT"])
def reorder_modules(self, request, *args, **kwargs):
"""
ReOrdering Modules
Sample request data
{
<module_id>: <ordering_number>
12: 2,
13: 1,
14, 3,
}
"""
updatabale_modules = []
for module_id, module_order in request.data.get("modules", {}).items():
_mod = Module.objects.get(id=module_id)
_mod.order = module_order
updatabale_modules.append(_mod)
Module.objects.bulk_update(updatabale_modules, ["order"])
return Response({"detail": "successfully reordered course modules"}, status=HTTP_200_OK)
Is there any way to avoid looping and getting each module?
If that's possible I should be able to save making a few queries.
FYI, I'm using MySQL database.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
代替直接查询
module.objects.get(id = module_id)
,您可以实例化module
对象使用:模块(id = model_id)
,因此将您的方法重写为:我使用Query Inspector调试此视图,它确实仅产生一个DB查询,并且可以与不存在的IDS一起使用
In stead of querying directly
Module.objects.get(id=module_id)
, you can instantiate aModule
object using:Module(id=model_id)
, so that rewrite your method to:I debugged this view with query inspector and it really produced only one db query, and it works with non-existent ids