在django中如何从字符串值创建模型实例? [英] In django how can i create a model instance from a string value?
本文介绍了在django中如何从字符串值创建模型实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所有
我有字符串表示我的模型和字段,像这样
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 )
...
我想做的是创建一个 MyModel 使用字符串变量,如
What i want to do is create an instance of MyModel using the string variables, something like
model_instance = modelNameStr.objects.filter(fieldNameStr=ForeignModelInstance)
我该怎么做?
Gath
推荐答案
model_instance = ContentType.objects.get(app_label=u'someapp', model=modelNameStr).model_class()(**{fieldNameStr: ForeignModelInstance})
hew!尝试说 五次快!但请确保您使用适当的值 app_label
。
Phew! Try saying that five times fast! But make sure you use the appropriate value for app_label
.
这篇关于在django中如何从字符串值创建模型实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文