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

时间:2022-08-02 17:02:28

I dont know if im clear with the title quiestion, what I want to do is the next case:

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

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

I just want to instantiate any models that I get via content types. After that I need to do something like form = create_form_from_model(ct_class) and get this model form ready to use.

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

Thank you in advance!.

先谢谢你!。

2 个解决方案

#1


33  

You need to create an instance of the class. ct.model_class() returns the class, not an instance of it. Try the following:

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

#2


5  

iPython or autocomplete is your best friend. Your problem is just that you are calling save on the Model itself. You need to call save on an instance.

iPython或autocomplete是你最好的朋友。您的问题只是您在模型本身上调用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(...)

#1


33  

You need to create an instance of the class. ct.model_class() returns the class, not an instance of it. Try the following:

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

#2


5  

iPython or autocomplete is your best friend. Your problem is just that you are calling save on the Model itself. You need to call save on an instance.

iPython或autocomplete是你最好的朋友。您的问题只是您在模型本身上调用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(...)