I am new to django and django-rest-framework and I am wondering if it is possible to put conditional if else on annotate(total_sessions=Count()) where if Count() = 0 then total_sessions="null"? I have a project where I need to make that if the total sessions is equal to 0 the output must be null.
I though of using SerializerMethodField() on total_sessions to get the count but this cause multiple SQL queries causing slow API response that is why it is out of the question.
Sample code below for serializers.py and views.py(this is only a sample code as my real codes have multiple querysets).
serializers.py
class ClassStatisticsSerializer(ModelBaseSerializer):
total_sessions = serializers.IntegerField()
class Meta:
model = Class
fields = (
'id',
'batch',
'type,
'total_sessions'
)
views.py
from django.db.models import Count, Q
class ClassStatisticsList(APIView):
condition = {}
if date:
condition = {'classactivity__date':date}
queryset = Class.objects.all().annotate(
total_sessions=Count(
'classactivity',
filter=Q(**condition),
distinct=True
)
)
You are looking for Conditional Expressions that are documented nicely on the Django site.
I haven't tried the following snippet (it's just your code augmented), it's just to give you a starting point:
queryset = Class.objects.all()
.annotate(
total_session_cnt=Count(
'classactivity',
filter=Q(**condition),
distinct=True
)
)
.annotate(
total_sessions=Case(
When(total_session_count=0, then=Value(None, output_field=IntegerField())),
default='total_session_count'
)
)