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

时间:2011-02-01 13:46:41

标签: python django django-models content-type

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

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()

3 个答案:

答案 0 :(得分:61)

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

self.__class__.__name__

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

ContentType.objects.get_for_model(self)

答案 1 :(得分:1)

方法function groupTeams(teams, group_count) { var groups = []; var current_group = 0; for ( var i = 0; i < teams.length; i++ ) { // make sure that the group is an array if ( !groups[ current_group ] ) { groups[ current_group ] = [] } // add the team groups[current_group].push( teams[i] ) // and move to the next group current_group += 1; // go back to the beginning if we hit the end. if ( current_group >= group_count ) { current_group = 0 } } return groups; } 做一些花哨的东西,但是在某些情况下最好不要使用这些花哨的东西。特别是说您想过滤链接到ContentType的模型,也许是通过通用外键?这里的问题是在{p> 1中对var teams = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']; // groups becomes array of 4 arrays containing the teams in each group var groups = groupTeams( teams, 4 ); // and you can use the array functions to get metadata about these groups, such as their size... var group_totals = groups.map( g => g.length ) // update UI based on groups 使用什么

  

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

使用get_for_model,或者如果您有model_name对象,那么Foo._meta.model_name是您要寻找的对象。然后,您可以执行类似的操作

Foo

这是过滤obj._meta.model_name表以返回对象的有效方法,这些对象通过名为Bar.objects.filter(content_type__model=Foo._meta.model_name) 的字段链接到Bar内容类型。

答案 2 :(得分:0)

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

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

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