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

Sei*_*dis 40 python django content-type django-models

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

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
Run Code Online (Sandbox Code Playgroud)

这段代码有效,但我必须知道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()
Run Code Online (Sandbox Code Playgroud)

gra*_*pot 65

您可以从对象中获取模型名称,如下所示:

self.__class__.__name__
Run Code Online (Sandbox Code Playgroud)

如果你更喜欢内容类型,你应该能够这样:

ContentType.objects.get_for_model(self)
Run Code Online (Sandbox Code Playgroud)

  • 通过`ContentType`的解决方案需要额外的SQL请求. (3认同)

Ala*_*nSE 9

该方法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)
Run Code Online (Sandbox Code Playgroud)

这是过滤Bar表以返回Foo通过名为 的字段链接到内容类型的对象的有效方法content_type


Pab*_*ero 5

使用gravelpot的答案,直接回答OP的问题:

我们可以获取对象的类instance.__class__,然后将其传递给 get_for_model函数:

from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(instance.__class__)
Run Code Online (Sandbox Code Playgroud)