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 seed Django project ? – insert a bunch of data into the project for initialization

Similar to Rails, we also have option to seed the database. It is done using management commands. In one of your apps, use the following folder structure <project>/<app>/management/commands/seed.py this makes python manage.py seed available as a management command. I personally follow the following structure. # <project>/<app>/management/commands/seed.py from django.core.management.base import BaseCommand import random # python manage.py …

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