【问题标题】:django content types - how to get model class of content type to create a instance?django 内容类型 - 如何获取内容类型的模型类来创建实例?
【发布时间】:2011-03-22 02:33:20
【问题描述】:

我不知道我是否清楚标题问题,我想做的是下一个案例:

>>> 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) 并准备好使用此模型表单。

提前谢谢你!

【问题讨论】:

    标签: python django django-contenttypes


    【解决方案1】:

    您需要创建该类的一个实例。 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()
    

    【讨论】:

    • cool!,如果我想创建查询集:ct_instance.__class__.objects.all() - 有了这个,我可以使用表单集工厂来创建我需要的所有实例的动态表单。谢谢!
    • 你也可以直接从类中获取查询集 - ct_class.objects.all()
    【解决方案2】:

    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(...)
    

    【讨论】:

      猜你喜欢
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多