manually create a Django QuerySet or rather manually add objects to a QuerySet

If you’re simply looking to create a queryset of items that you choose through some complicated process not representable in SQL you could always use the __in operator. wanted_items = set() for item in model1.objects.all(): if check_want_item(item): wanted_items.add(item.pk) return model1.objects.filter(pk__in = wanted_items) You’ll obviously have to adapt this to your situation but it should at … Read more

Django ‘objects.filter()’ with list?

You mean like this? my_model.objects.filter(creator__in=creator_list) Docs: http://docs.djangoproject.com/en/dev/ref/models/querysets/#in EDIT This is now a bit outdated. If you run into problems with the original code, try this: from django.db.models import Q my_filter_qs = Q() for creator in creator_list: my_filter_qs = my_filter_qs | Q(creator=creator) my_model.objects.filter(my_filter_qs) There’s probably a better way to do it but I’m not able to … Read more

How do I retrieve a Django model class dynamically?

I think you’re looking for this: from django.db.models.loading import get_model model = get_model(‘app_name’, ‘model_name’) There are other methods, of course, but this is the way I’d handle it if you don’t know what models file you need to import into your namespace. (Note there’s really no way to safely get a model without first knowing … Read more

how to create an empty queryset and to add objects manually in django [closed]

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

Django : Filter query based on custom function

I just had a similar issue. The problem was i had to return a QuerySet instance. A quick solution for me was to do something like this: active_serv_ids = [service.id for service in Service.objects.all() if service.is_active()] nserv = Service.objects.filter(id__in=active_serv_ids) I’m pretty sure this is not the prettiest and performant way to do this, but it … Read more