3

All,

I have strings that represent my model and fields, like this

modelNameStr = 'MyModel'
fieldNameStr = 'modelField'

My model looks like this;

class MyModel(models.Model):
    modelField = ForeignKey( ForeignModel )
    ...

What i want to do is create an instance of MyModel using the string variables, something like

model_instance = modelNameStr.objects.filter(fieldNameStr=ForeignModelInstance)

How can i do this?

Gath

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How can we use the filter with ContentType?
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.