How to update a slice set, in an elegant way?

…衆ロ難τιáo~ 提交于 2019-12-11 14:56:01

问题


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)

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

Does that mean CAN NOT WRITE UPDATE ... WHERE ... LIMIT 5?


回答1:


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.




回答2:


You can try this

users = MyTable.objects.order_by('-month_length').values_list("id", flat = True)[0: 250]
MyTable.objects.filter(id__in = list(users)).update(top = 1)

*assuming you have a primary key 'id' in MyTable



来源:https://stackoverflow.com/questions/25011513/how-to-update-a-slice-set-in-an-elegant-way

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!