Reputation: 968
I have a queryset :-
queryset = my_object.someobject_set.all()
From there onwards, I want to filter from the queryset. i.e:
print queryset.filter(name='some1').exists()
print queryset.filter(name='some2').exists()
print queryset.filter(name='some3').exists()
But for each of the filter queries, there is a database hit again. How can I cache the queryset and then filter from it?
I even tried to evaluate the queryset before filtering by doing this:-
print len(queryset)
But this doesn't work. Any help??
Upvotes: 1
Views: 2685
Reputation: 15370
It is not possible with django ORM. But you can do that in python.
queryset = list(my_object.someobject_set.all())
print list(filter(lambda i: i.name == 'some1', queryset))
print list(filter(lambda i: i.name == 'some2', queryset))
print list(filter(lambda i: i.name == 'some3', queryset))
This way you won't do any additional db hits. But if this queryset is really big than it is better to do it with ORM, even if it hits db. Time it for yourself and see which one is faster
Upvotes: 4