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

标签 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)

我只想实例化通过内容类型获得的任何模型。 之后我需要做类似 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/

相关文章:

django - 如何在 virtualbox/vagrant 服务器中访问 django 网站?

django-rest-framework用于ContentType对象的序列化器

django - 使用 Django Rest Framework 序列化通用关系,并提供写入支持

python - 使用Django泛型关系时如何进行正确的反向查询?

python - 发布到 Facebook 页面墙 - 使用 Graph API?

python - “tee”不被识别为内部或外部命令、可操作程序或批处理文件

python - 2.x 中 python 类样式的建议是什么,最终更新到 3.x

python - Django不能上传文件和图片

python - Django 信号卡在循环中

python - Django模型ForeignKey关系