Home > Blockchain >  Access value of row using Django's Case/When queryset conditions
Access value of row using Django's Case/When queryset conditions

Time:03-10

I'm trying to migrate some value in Django, I'm using the Django model's When-Case. My implementation is simple, it worked with static string:

When(
            description__in=pre_desc,
            then=Value("pre-string"),
        ),
        When(
            description__in=post_desc,
            then=Value("some-post-string"),
        )

This code above works. But the problem arises when I try to add something before or after to existing string:

pre_desc = ["a", "b", "c"]
post_desc = ["a", "b", "c"]


StoreO.objects.filter().update(
    description=Case(
        When(
            description__in=pre_desc,
            then=Value("pre-string" description),
        ),
        When(
            description__in=post_desc,
            then=Value(description "some-post-string"),
        ),
        default=Value("def_str")),
    )
)

It says, description is not defined. Can anyone give me some workaround?

I also tried str(F('description') 'randomstr') which resulted in F('description') 'randomstr' in the db.

CodePudding user response:

You reference a field with an F expression [Django-doc], or here you concatenate the string with Concat [Django-doc]:

from django.db.models.functions import Concat

pre_desc = ['a', 'b', 'c']
post_desc = ['a', 'b', 'c']

StoreO.objects.all().update(
    description=Case(
        When(
            description__in=pre_desc,
            then=Concat(Value('pre-string'), 'description'),
        ),
        When(
            description__in=post_desc,
            then=Concat('description', Value('some-post-string')),
        ),
        default=Value('def_str')),
    )
)
  • Related