Piotr Czapla Piotr Czapla - 6 months ago 31
Python Question

Duplicate django query set?

I have a simple django's query set like:

qs = AModel.objects.exclude(state="F").order_by("order")


I'd like to use it as follows:

qs[0:3].update(state='F')
expected = qs[3] # throws error here


But last statement throws:
"Cannot update a query once a slice has been taken."

How can I duplicate the query set?

Answer

It's the first line throwing the error: you can't do qs[0:3].update(). qs[0:3] is taking a slice; update() is updating the query.

update() is meant for bulk updates, resulting in SQL queries like

UPDATE app_model SET state = 'F' WHERE state <> 'F';

You're trying to update the first three items according to "order", but that can't be done with this type of UPDATE--you can't order or limit an SQL UPDATE. It needs to be written differently, eg.

UPDATE app_model SET state = 'F' WHERE id IN (
    SELECT id FROM app_model WHERE state <> 'F' ORDER BY order LIMIT 3
) AS sub;

but Django can't do that for you.