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)
该方法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
。
使用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)
归档时间: |
|
查看次数: |
26649 次 |
最近记录: |