如何以一种优雅的方式更新切片集? [英] How to update a slice set, in an elegant way?

查看:42
本文介绍了如何以一种优雅的方式更新切片集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我想要排名前250位的用户,并更新其 top = 1

First, I want the top 250 users, and update their top = 1

users = MyTable.objects.order_by('-month_length')[0: 250]
for u in users:
    u.top = 1
    u.save()

但是,实际上,我希望有这样一种优雅的方式:

But, actually, I hope there is an elegent way, like this:

MyTable.objects.all().update(top=1)

以及更多有关此问题的信息:Django:获取切片后无法更新查询

And more, from this question: Django: Cannot update a query once a slice has been taken

这是否意味着不能写 UPDATE ... WHERE ... LIMIT 5 ?

推荐答案

在对查询集进行一次评估之前(此时它将自身进行缓存),将结果切成新的查询集.如果查询集已被缓存,则使用列表进行切片.至少上一次我阅读有关Django的代码,大概是在Django 1.5左右.

Until the queryset has been evaluated once (at which point it will cache itself), slicing result in new querysets. If the queryset has been cached, slicing is done using lists. At least the last time I read the Django code regarding this, probably around Django 1.5.

这篇关于如何以一种优雅的方式更新切片集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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