[Answered ]-DRF How to optimize this query, instead of looping if's?

2๐Ÿ‘

โœ…

As the iron maiden @anderson-lima has pointed out, this is a problem with your data rather than your code. You do not have an image with order = 0 and your first method handles that situation correct if not optimally.

@staticmethod
    def get_image(obj):
        for d in obj.images.all():
            if d.order == 0:
                return d.filename

        # returns None here if an object with order = 0
        # does not exist in the database.

However in your second approach you are taking a slice but fetching an object that does not exist. Hence the execption, and which in turn tells us that what you need is a just a try except block.

@staticmethod
def get_image(obj):
    try:
        return obj.images.filter(order=0)[0].filename
    except IndexError:
        return None
๐Ÿ‘คe4c5

Leave a comment