I have a list of id and sort:
ids = ['123', '456', '789', '901'];
sorts = [1, 3, 2, 4];
I want to update the order of each id in Django.
Here is the SQL and Django i have tried:
SQL:
UPDATE "Blogs"
SET sort = CASE
WHEN id = '123' THEN 1
WHEN id = '456' THEN 3
WHEN id = '789' THEN 2
WHEN id = '901' THEN 4
END
WHERE id IN (ids);
Django:
Blogs.objects.filter(
id=ids
).update(
sort=Case(
When(id=123, then=1),
When(id=456, then=3),
When(id=789, then=2),
When(id=901, then=4),
)
)
But problem is when ids have many elements I can not specific id and then in When(id={id}, then={sort}).
How can I optimize the update query in Django version.
Thanks in advance.