I have a SQL query and when writing in Django ORM it returns an error. But the SQL query works perfectly on MySQL Command Line Client. Would anyone please explain the error or working of CASE and When in Django ORM?
SQL query:-
SELECT CASE WHEN LENGTH(au.first_name) < 1 THEN au.username ELSE concat(au.first_name,' ',au.last_name)
END AS fullname FROM rewards_usercard ru RIGHT JOIN auth_user au ON ru.user_id = au.id;
Django Models code:-
from django.db.models import Case, When, Q, CharField, Value
from django.db.models.functions import Length, Concat
from django.db.models.lookups import LessThan
queryset = UserCard.objects.annotate(
full_name = Case(
When(condition=Q(
LessThan(Length('user__first_name'),1)
), then='user__username'),
default = Concat('user__first_name', Value(' '), 'user__last_name'),
output_field=CharField()
)
)
Error:-
cannot unpack non-iterable LessThan object
CodePudding user response:
Try this:
from django.db.models.functions import Coalesce, Concat
from django.db.models import (Case, CharField, When, Value)
data = UserCard.objects.all().annotate(fullname=Coalesce(Case(When(user__first_name__in=[None, ""], then="user__username"),default=Concat('user__first_name',Value(" "), 'user__last_name'),output_field=CharField()),"user__username")).values('fullname')