1

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??

Abhinav Nair
  • 958
  • 1
  • 8
  • 29

1 Answers1

4

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

Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
  • 1
    no need to fetch all columns into memory. use `only` instead. – itzMEonTV Oct 05 '16 at 07:03
  • @itzmeontv I'm not sure that he just wants to check if values exists or not. But yes, if this needed only for checking `only` is way to go. – Sardorbek Imomaliev Oct 05 '16 at 07:04
  • what you think of ? looping over lists and check for a field vs 'exists' query to db ?answer from your knowledge? :) – itzMEonTV Oct 05 '16 at 07:11
  • @itzmeontv are you asking in general? – Sardorbek Imomaliev Oct 05 '16 at 07:14
  • yes, sometimes i am thinking doing `exist` is best than loop over. – itzMEonTV Oct 05 '16 at 07:16
  • @itzmeontv It really depends. Sometimes your DB located on another machine, so there will be network ping(should be taken to account). If there is millions of rows and DB on same server, then yes `exist` is probably faster. But for small querysets it is better to do in python. Because usually openning connections is very time expensive. – Sardorbek Imomaliev Oct 05 '16 at 07:20