2011-02-01 49 views
31

假設我在保存代碼中。我如何獲取模型的名稱或對象的內容類型,並使用它?如何獲取模型的名稱或Django對象的內容類型?

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

回答

53

您可以從對象獲取的型號名稱如下:

self.__class__.__name__ 

如果你喜歡的內容類型,你應該可以得到這樣的:

ContentType.objects.get_for_model(self) 
+0

如果您有數據庫瀏覽器工具,則可以看到創建了django_content_type。它包含一些字段,如名稱,app_label和模型。我需要從我所在的類中獲取該模型信息。 – Seitaridis 2011-02-01 14:20:19