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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With