django内容类型 - 如何获取内容类型的模型类来创建实例?

pan*_*ore 23 python django django-contenttypes

我不知道如果我清楚标题静止,我想做的是下一个案例:

>>> 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)
Run Code Online (Sandbox Code Playgroud)

我只想实例化我通过内容类型获得的任何模型.之后我需要做类似的事情, form = create_form_from_model(ct_class) 并准备好使用这个模型表单.

先感谢您!.

Bla*_*air 42

您需要创建该类的实例.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()
Run Code Online (Sandbox Code Playgroud)


Yuj*_*ita 6

iPython或autocomplete是你最好的朋友.你的问题只是你在调用Model自己.您需要在实例上调用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(...)
Run Code Online (Sandbox Code Playgroud)