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

问题描述 投票:35回答:2

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

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()
python django django-models content-type
2个回答
61
投票

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

self.__class__.__name__

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

ContentType.objects.get_for_model(self)

2
投票

方法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内容类型的对象的有效方法。

© www.soinside.com 2019 - 2024. All rights reserved.