Let's say I am in the save code. How can I obtain the model's name or the content type of the object, and use it?
假设我在保存代码中。如何获取模型的名称或对象的内容类型并使用它?
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
This code works, but I have to know the model_name:
这个代码可以工作,但是我必须知道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()
1 个解决方案
#1
57
You can get the model name from the object like this:
可以从对象中获取模型名,如下所示:
self.__class__.__name__
If you prefer the content type, you should be able to get that like this:
如果您喜欢内容类型,您应该能够得到如下内容:
ContentType.objects.get_for_model(self)
#1
57
You can get the model name from the object like this:
可以从对象中获取模型名,如下所示:
self.__class__.__name__
If you prefer the content type, you should be able to get that like this:
如果您喜欢内容类型,您应该能够得到如下内容:
ContentType.objects.get_for_model(self)