“一旦获取切片就无法更新查询".最佳做法? [英] "Cannot update a query once a slice has been taken". Best practices?

查看:37
本文介绍了“一旦获取切片就无法更新查询".最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我的项目的性质,我发现自己不断从查询集中提取切片,就像这样:

Because of the nature of my project, I find myself constantly taking slices out of querysets, like so:

Thread.objects.filter(board=requested_board_id).order_by('-updatedate')[:10]

但是这给我留下了一个问题,那就是我实际上在用我选择的元素做东西,因为任何类型的.update()或.filter()在切片后都无法工作.

But this leaves me with the problem of actually DOING stuff with the elements that I have selected, because any kind of .update() or .filter() won't work after slicing.

我知道解决它的几种方法,但是它们都很混乱和混乱,严重降低了代码的可读性,尤其是当我不得不经常这样做时.

I know of several ways to get around it, but they are all messy and confusing and seriously degrade the readability of the code, especially when I have to do it so often.

解决这种片状滤波器限制的最佳方法是什么?

What's the best way to get around this slice-filter limitation?

推荐答案

到目前为止,根据评论,我发现Daniel Roseman的解决方案最不丑":

So far, based on the comments, I have found this solution by Daniel Roseman to be the least "ugly":

sliced_queryset = Somemodel.objects.filter(field='fieldvalue')[:5]

然后使用 id__in = 引用切片的查询集对象的ID:

And then use id__in= to reference the sliced queryset objects' IDs:

Somemodel.objects.filter(id__in=sliced_queryset).update(field_to_update='whatever')

效果很好,我已经尝试过了.

It works well, I've just tried it.

我希望Django有一个更直接"的方式来做到这一点,但它仍然非常简单.如果有人有更好的方法,请发布它,我会将您的答案标记为正确.

I wish Django had a more 'direct' way of doing this, but it's still pretty straightforward. If anyone has a better way, please post it and I will mark your answer as correct.

作为一些额外的建议,如果您正在使用它来增加一个字段(例如视图"字段),则可以像这样干净地自引用它:

As a bit of extra advice, if you're using this to increment a field, like a 'views' field, you can self reference it cleanly like this:

from django.db.models import F

Somemodel.objects.filter(id__in=sliced_queryset).update(views=F('views')+1)

这篇关于“一旦获取切片就无法更新查询".最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆