[Django]-How to create an empty queryset and to add objects manually in django

36👍

You can do it in one of the following ways:

from itertools import chain
#compute the list dynamically here:
my_obj_list = list(obj1, obj2, ...)
#and then 
none_qs = MyModel.objects.none()
qs = list(chain(none_qs, my_obj_list))

You could also do:

none_qs = MyModel.objects.none()
qs = none_qs | sub_qs_1 | sub_qs_2

However, This would not work for sliced querysets

14👍

You can’t do that. A queryset is a representation of a database query. You can’t add items to it manually.

But if you need an arbitrary ordered collection of model instances, just use a list.

14👍

I’m really late to this one, but for a future reference you can create a queryset with all then filter for the objects that have a particular property.

Filtering on field object properties

Model.objects.filter(foo='bar')
Model.objects.exclude(foo='bar')

Filtering on non-field object properties

def return_queryset_with_desired_objects(self):
    qs = SomeModel.objects.all()
    wanted_ids = [obj.id for obj in qs if obj.foo]
    return self.filter(id__in=wanted_ids]

def return_queryset_without_undesired_objects(self):
    qs = SomeModel.objects.all()
    unwanted_ids = [obj.id for obj in qs if not obj.foo]
    return self.exclude(id__in=unwanted_ids]

Leave a comment