问题
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