我不知道标题是否清楚,我想要做的是下一个案例:
>>> 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)
这样的事情,让这个模型表单准备好使用。
提前谢谢你!
发布于 2011-03-22 10:38:51
您需要创建该类的一个实例。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()
发布于 2011-03-22 10:36:39
iPython或autocomplete是你最好的朋友。您的问题只是在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(...)
https://stackoverflow.com/questions/5386104
复制相似问题