开发者

In django how can i create a model instance from a string value?

开发者 https://www.devze.com 2023-03-19 08:00 出处:网络
All, I have strings that represent my model and fields, like this modelNameStr = \'MyModel\' fieldNameStr = \'modelField\'

All,

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

modelNameStr = 'MyModel'
fieldNameStr = 'modelField'

My model looks like this;开发者_如何学JAVA

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


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.


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消