Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an evaluated QuerySet in Django

Tags:

python

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.

like image 505
Brian Cray Avatar asked Jan 30 '26 11:01

Brian Cray


1 Answers

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')
like image 120
Aamir Rind Avatar answered Feb 02 '26 02:02

Aamir Rind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!