pythondjangocode-inspection

Simplify function code while maintaining readability


This code works, but seems too redundant to me.

Is it possible to somehow simplify it while maintaining functionality and readability?

has_videos = self.request.query_params.get('has_videos')
if has_videos:
    if has_videos == 'true':
        entries = User.objects.filter(videos__isnull=False)
    elif has_videos == 'false':
        entries = User.objects.filter(videos__isnull=True)
else:
    entries = User.objects.all()

I tried to write in one line using the ternary operator, but the readability disappeared completely

entries = Pet.objects.all() if has_photos not in ['true', 'false'] \
else Pet.objects.filter(photos__isnull=False) if has_photos == 'true' \
else Pet.objects.filter(photos__isnull=True)

Solution

  • Delete the outer if statement.

    if has_videos == 'true':
        entries = User.objects.filter(videos__isnull=False)
    elif has_videos == 'false':
        entries = User.objects.filter(videos__isnull=True)
    else:
        entries = User.objects.all()
    

    Less duplication, still readable(?).

    d = {'true':False, 'false':True}
    try:
        entries = User.objects.filter(videos__isnull=d[has_videos])
    except KeyError:
        entries = User.objects.all()