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:

my_objects = MyObject.objects.all()

And I evaluate it with something like:

len(my_objects)

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):

my_objects = MyObject.objects.all()
obj_dict = {obj.name: obj for obj in my_objects}
print obj_dict['any_name']

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

obj = MyObject.objects.get(pk=id)
or
obj = MyObject.objects.get(name='unique_name')
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement