65

It seems like a django queryset behaves somehow like a python list.

But it doesn't support list's .append() method as I know.

What I want to do is like:

from my_django_app.models import MyModel

queryset = MyModel.objects.none()
queryset.append(MyModel.objects.first())      ## no list's .append() method!

Is there any way to add an model instance to an existing queryset?

4 Answers 4

76

You can also use the | operator to create a union:

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

But be warned that this will generate different queries depending on the number of items you append this way, making caching of compiled queries inefficient.

2
  • Can anyone suggest more efficient manner for this? Jan 9 at 12:11
  • Depends on what you need. E.g. do you have many instances to add? Maybe .filter(pk__in=...) works for you. Jan 12 at 17:32
32

No. A queryset is a representation of a query - hence the name - not an arbitrary collection of instances.

If you really need an actual queryset rather than a list, you could try accumulating the IDs of the objects you need and then getting the objects via an __in query:

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

This isn't very efficient, though.

1
  • 2
    Why is this one disagreeing with the others? Not qute following why both have substantial + votes May 10, 2022 at 13:27
19

This can be done using union. After doing this, the type of the result can be seen as <class 'django.db.models.query.QuerySet'>. So two querysets can be combined. Lets see an example.

query1 = User.objects.filter(is_active=True)

query2 = User.objects.filter(is_active=False)

combined_query = query1.union(query2)

print (type(combined_query))

The above program will print result as below, confirming it is a queryset

<class 'django.db.models.query.QuerySet'>

So basically Django executes the below query for union.

(SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."is_active" = True) 
UNION 
(SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."is_active" = False)

This also means that there will be error(django.db.utils.ProgrammingError: each UNION query must have the same number of columns) if union is tried with two different tables.

2
  • 4
    Beware: the QuerySet returned by union() has limitations. For example, it cannot be filtered again. See union documentation for details. Also see my example here.
    – djvg
    Jul 23, 2020 at 10:11
  • For a reason I do not fully understand, calling .union(qs2) was the solution for me. Using the | operator seemed to create a brand new query combining the existing two, which resulted in a different result than just the union. Mar 18, 2022 at 14:51
9

Queryset is not a list

So

to_list = queryset.values()

To combine queryset

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

or

querysets = [queryset1, queryset2]
result_queryset = list(chain(*querysets))
3
  • What I'm trying to do is to accumulate some model instances to an queryset and return the queryset rather than an python list. Is there any way to do this?
    – June
    Apr 12, 2015 at 8:28
  • You are eventually getting an list (result_queryset), not a queryset.
    – June
    Apr 12, 2015 at 8:42
  • does not work, getting exception that it is not iterable Jul 22, 2019 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.