Django empty char ('') to null (NULL) inside Coalesce statement

I have the following query that I would like to execute:

MyModel.objects.annotate(current_name=Coalesce('nickname', 'name')).order_by('current_name') 

which fails because the alias is not NULL when empty, but it is an empty char (as is customary in the Django community).

So I would like to do something like:

MyModel.objects.annotate(if empty char: make null, then do coalesce like above). Is this possible?
+4
source share
1 answer

Use conditional expressions that are new in Django 1.8.

from django.db.models import CharField, Case, When
from django.db.models.functions import Coalesce

MyModel.objects.annotate(
    current_name=Coalesce(
        Case(
            When(nickname__exact='', then=None),
            When(nickname__isnull=False, then='nickname'),
            default=None,
            output_field=CharField()
        ),
        Case(
            When(name__exact='', then=None),
            When(name__isnull=False, then='name'),
            default=None,
            output_field=CharField()
    ))).order_by('current_name')
+6
source

Source: https://habr.com/ru/post/1625949/


All Articles