Adding a query set to a list / tuple without evaluating it

According to docs, the query gets evaluated when list () is called on it.

Is there a way to add a list / tuple with a set of queries instead of model objects? Is list () called for each operation on lists / tuples?

eg:

foo= Foo.objects.all() bar = Bar.objects.filter(enabled=True) my_list = [] my_list.append(foo) <-- evaluates my_list.extend(foo) <-- evaluates my_tuple = () my_tuple = my_tuple + (foo,) <-- evaluates # so I'm getting [<Foo: ModelDescription>,<Foo: ModelDescription>,<Bar: ModelDescription>] #but I want [<Queryset: Foo>, <Queryset:Bar>] 
+4
source share
1 answer

This is either no longer true, or perhaps the way you checked the type of elements inadvertently caused an estimate.

To summarize, you can use append() or my_tuple = my_tuple + (foo,) . If you try to just print them, it will evaluate the QuerySet and display their contents, but if you scroll through these collections, you can work with the actual QuerySet .

 >>> a = Author.objects.filter() >>> b = Book.objects.filter() >>> type(a), type(b) (<class 'django.db.models.query.QuerySet'>, <class 'django.db.models.query.QuerySet'>) >>> l = [] >>> l.append(a) >>> l.append(b) >>> type(l[0]), type(l[1]) (<class 'django.db.models.query.QuerySet'>, <class 'django.db.models.query.QuerySet'>) >>> for q in l: ... print type(q) ... <class 'django.db.models.query.QuerySet'> <class 'django.db.models.query.QuerySet'> >>> my_tuple = () >>> my_tuple = my_tuple + (a,) >>> type(my_tuple[0]) <class 'django.db.models.query.QuerySet'> >>> len(l) 2 >>> len(my_tuple) 1 >>> print l [[<Author: Author object>, '...(remaining elements truncated)...'], [<Book: Book object>,]] >>> len(my_tuple) 1 >>> print my_tuple ([<Author: Author object>, '...(remaining elements truncated)...'],) >>> len(my_tuple) 1 >>> 
0
source

Source: https://habr.com/ru/post/1485432/


All Articles