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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4863332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:52:25  来源:igfitidea点击:

How can I obtain the model's name or the content type of a Django object?

pythondjangodjango-modelscontent-type

提问by Seitaridis

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:

此代码有效,但我必须知道模型名称:

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

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

采纳答案by gravelpot

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)

回答by AlanSE

The method get_for_modeldoes some fancy stuff, but there are some cases when it's better to not use that fancy stuff. In particular, say you wanted to filter a model that linked to ContentType, maybe via a generic foreign key?? The question here was what to use for model_namein:

该方法get_for_model做了一些花哨的东西,但在某些情况下最好不要使用那些花哨的东西。特别是,假设您想过滤链接到 ContentType 的模型,可能通过通用外键?这里的问题是用于什么model_name

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

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

Use Foo._meta.model_name, or if you have a Fooobject, then obj._meta.model_nameis what you're looking for. Then, you can do things like

使用Foo._meta.model_name,或者如果您有一个Foo对象,那么obj._meta.model_name这就是您要查找的内容。然后,您可以执行以下操作

Bar.objects.filter(content_type__model=Foo._meta.model_name)

This is an efficient way to filter the Bartable to return you objects which link to the Foocontent type via a field named content_type.

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