Search code examples
djangofilterdjango-queryset

Django filter queryst after retrieving


I'm making a django website and due to the load on the database I'd like to filter the queryset after retrieving it.

files = Files.objects.get(folder_id=folder_id)

first_file = files.objects.filter(sequence = 0)

This example throws me error, same if I tried for loop. So is it possible to filter the retrieved queryset without interacting with database ?


Solution

  • when you run get that executes the query, returns a single Files object. https://docs.djangoproject.com/en/4.1/ref/models/querysets/#get

    you would want to change the first line to filter (which won't actually execute the query yet) https://docs.djangoproject.com/en/4.1/ref/models/querysets/#filter

    and the second line to get.

    files = Files.objects.filter(folder_id=folder_id)
    
    first_file = files.objects.get(sequence = 0)