我不知道我是否清楚标题问题,我想做的是下一个案例:
>>> 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)
并准备好使用此模型表单。
提前谢谢你!
最佳答案
您需要创建该类的一个实例。 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()
关于python - django 内容类型 - 如何获取内容类型的模型类来创建实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5386104/