[Django]-In django how can i create a model instance from a string value?

5👍

model_instance = ContentType.objects.get(app_label=u'someapp', model=modelNameStr).model_class()(**{fieldNameStr: ForeignModelInstance})

Phew! Try saying that five times fast! But make sure you use the appropriate value for app_label.

3👍

Retrieving the model class you can use the get_model function from Django. Though you have to use a string like my_app.MyModel where ‘my_app’ is your django app which includes the model. Filtering field values can be achieved via a dict. Here an example:

from django.db.models import get_model

modelNameStr = 'my_app.MyModel'
fieldNameStr = 'modelField'

ModelClass = get_model(*model_class.split('.'))
filters = {fieldNameStr: ForeignModelInstance}

model_instance = ModelClass.objects.filter(**filters)

Leave a comment