Django 内容类型 - 如何获取内容类型的模型类以创建实例?
我不确定我的标题问题是否表达清楚,我想做的事情是这样的:
>>> from django.contrib.contenttypes.models import ContentType
>>> ct = ContentType.objects.get(model='user')
>>> ct.model_class()
<class 'django.contrib.auth.models.User'>
>>> ct_class = ct.model_class()
>>> ct_class.username = 'hellow'
>>> ct_class.save()
TypeError: unbound method save() must be called with User instance as first argument (got nothing instead)
我只是想根据内容类型创建一些模型实例。之后,我需要做类似于 form = create_form_from_model(ct_class)
的操作,把这个模型的表单准备好可以使用。
提前谢谢大家!
2 个回答
8
iPython或者自动补全功能是你最好的帮手。你的问题在于你直接在Model
上调用了save方法。其实你应该在一个实例上调用save。
ContentType.objects.latest('id').model_class()
some_ctype_model_instance = some_ctype.model_class()()
some_ctype_model_instance.user = user
some_ctype_model_instance.save()
some_instance = some_ctype.model_class().create(...)
60
你需要创建这个类的一个实例。ct.model_class()
返回的是这个类本身,而不是它的一个实例。你可以试试下面的代码:
>>> from django.contrib.contenttypes.models import ContentType
>>> ct = ContentType.objects.get(model='user')
>>> ct_class = ct.model_class()
>>> ct_instance = ct_class()
>>> ct_instance.username = 'hellow'
>>> ct_instance.save()