如何获取Django对象的模型名称或内容类型?

61 投票
3 回答
45747 浏览
提问于 2025-04-16 11:00

假设我正在保存代码。我该如何获取模型的名称或者对象的内容类型,并使用它呢?

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

这段代码可以正常工作,但我必须知道模型的名称:

import django.db.models
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get(model=model_name)
model = content_type.model_class()

3 个回答

5

根据gravelpot的回答,直接回答提问者的问题:

我们可以通过 instance.__class__ 来获取对象的类别,然后把这个类别传递给 get_for_model 函数:

from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(instance.__class__)
11

方法 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 表,返回那些通过名为 content_type 的字段链接到 Foo 内容类型的对象。

113

你可以通过这个方法从对象中获取模型名称:

self.__class__.__name__

如果你想获取内容类型,可以用下面的方法:

from django.contrib.contenttypes.models import ContentType
ContentType.objects.get_for_model(self)

撰写回答