How can I set and append in column with conditional case in Django?

Question:

I want to run this sql query in Django

UPDATE `TABLE` SET `COLUMN` = (CASE WHEN `COLUMN` = "" THEN '100' ELSE CONCAT(`COLUMN`,'100') END)
WHERE `SOMEID` IN [id1,id2,id3];

I tried this

from django.db.models import Case, When, F
Table.objects.filter(someid__in=[id1,id2,id3]).
update(column=
  Case(
    When(column="",then="100"),
    default= column + "100",
  )
)

I dont know how to put concat in default here.

Asked By: Anonymous

||

Answers:

You can use the F objects:

from django.db.models import F

Table.objects.filter(...).update(column=F("column") + "100")

You don’t need to check if column == "" because it won’t matter when you append "100" to it.

Answered By: Selcuk
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.