Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying a django model using a model name string 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 the django ORM, i am trying to read a string which will be the name of a model, and use it to query. Something like this:

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

This will obviously not work as it is a string. I have looked at ContentType but i am not sure how it will be helpful in my scenario. Any suggestions?

I also tried doing a get operation on Contentype like this:

>>> 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 proceed further from here!

like image 311
Abhishek Avatar asked Apr 13 '15 01:04

Abhishek


Video Answer


1 Answers

If you're using Django < 1.7, I think you can do this.

from django.db.models.loading import get_model

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

For django >= 1.7, you can

from django.apps import apps

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

you can then use ModelB to query.

like image 153
Rod Xavier Avatar answered Nov 15 '22 07:11

Rod Xavier