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.
- [Django]-Django TemplateSyntaxError – 'staticfiles' is not a registered tag library
- [Django]-How to use Python type hints with Django QuerySet?
- [Django]-Django model method – create_or_update
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]
- [Django]-Object has no attribute 'get'
- [Django]-How do I start up remote debugging with PyCharm?
- [Django]-Django vs. Model View Controller
Source:stackexchange.com