Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading