Skip to content
Advertisement

Filter an evaluated QuerySet in Django

The requirement is for me to be able to access members of an evaluated QuerySet by a string attribute, in this case name. I don’t like the idea of looping over a QuerySet as it seems like there is a more efficient way.

After I’ve called something like:

JavaScript

And I evaluate it with something like:

JavaScript

What is the best way to get a specific result by name from an evaluated QuerySet, in this case my_objects? Ideally I’d like to see something like my_objects.filter(foo='bar').

Note I’ll need all of the results in the evaluated QuerySet during the course of the process, so that’s why I have it in one initial query.

Advertisement

Answer

There is no direct way of doing this to get a object based on field value from queryset. But you can do one thing is to create a dictionary from queryset and set name as key (must be unique):

JavaScript

FYI: If you want to just retrieve a single object from table then you can use .get method:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement