Querying a django model using model name input

Let's say I have the following django models:

class ModelB(models.Model):
    title = models.CharField(max_length=20)

class ModelD(models.Model):
    name = models.CharField(max_length=20)

In django ORM I am trying to read a line , which will be the name of the model , and use it for the query. Something like that:

>>b = 'ModelB'
>>b.objects.all()

This obviously does not work as it is a string. I looked at ContentType , but I'm not sure how this will be useful in my scenario. Any suggestions?

I also tried to perform the operation geton Contentypeas follows:

>>> z = ContentType.objects.get(model='modelb')
>>> z
<ContentType: model b>
>>> z.__dict__
{'model': u'modelb', '_state': <django.db.models.base.ModelState object at 0x7f195346c150>, 'id': 14, 'app_label': u'testapp'}
>>>

But I did not know how to move on further!

+4
source share
1 answer

If you use Django <1.7, I think you can do it.

from django.db.models.loading import get_model

z = ContentType.objects.get(model='modelb')
ModelB = get_model(z.app_label, 'ModelB')

django >= 1.7

from django.apps import apps

z = ContentType.objects.get(model='modelb')
ModelB = apps.get_model(z.app_label, 'ModelB')

ModelB .

+8

All Articles