假设我在保存代码中。如何获取对象的模型名称或内容类型,并使用它?
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__
如果你更喜欢内容类型,你应该能够这样:
ContentType.objects.get_for_model(self)
方法get_for_model
做了一些奇特的东西,但有些情况下,最好不要使用那些花哨的东西。特别是,假设你想过滤一个链接到ContentType的模型,可能是通过一般的外键?这里的问题是如何使用model_name
:
content_type = ContentType.objects.get(model = model_name)
使用Foo._meta.model_name
,或者如果你有Foo
对象,那么obj._meta.model_name
就是你要找的东西。然后,你可以做的事情
Bar.objects.filter(content_type__model=Foo._meta.model_name)
这是过滤Bar
表以返回通过名为Foo
的字段链接到content_type
内容类型的对象的有效方法。