How to add model instance to django request set?

The django query seems to behave somewhat like a python list.

But it does not support the listapp () method, as I know.

I want to do the following:

from my_django_app.models import MyModel queryset = MyModel.objects.none() queryset.append(MyModel.objects.first()) ## no list .append() method! 

Is there a way to add a model instance to an existing set of queries?

+6
source share
3 answers

No. A query set is a representation of a query β€” hence, a name is not an arbitrary set of instances.

If you really need the actual set of queries, not a list, you can try to collect the identifiers of the objects you need, and then get the objects through the __in request:

 list_of_ids = [] list_of_ids.append(my_id) ... queryset = MyModel.objects.filter(id__in=list_of_ids) 

It is not very effective.

+7
source

You can also use the | To create a union:

 queryset = MyModel.objects.none() instance = MyModel.objects.first() queryset |= MyModel.objects.filter(pk=instance.pk) 

But be careful, this will lead to the generation of various queries depending on the number of elements that you added in this way, making caching of compiled queries inefficient.

+2
source

Queryset is not a list

So,

 to_list = queryset.values() 

Combine queryset

 from itertools import chain result_queryset = list(chain(queryset1, queryset2)) 

or

 querysets = [queryset1, queryset2] result_queryset = list(chain(*querysets)) 
+1
source

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


All Articles