假设我在保存代码中。如何获取模型的名称或对象的内容类型并使用它?
from django.db import models
class Foo(models.Model):
...
def save(self):
I am here....I want to obtain the model_name or the content type of the object
此代码有效,但我必须知道 model_name:
import django.db.models
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get(model=model_name)
model = content_type.model_class()
您可以从对象中获取模型名称,如下所示:
self.__class__.__name__
如果您更喜欢内容类型,您应该能够像这样获得:
from django.contrib.contenttypes.models import ContentType
ContentType.objects.get_for_model(self)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)