2010-04-30 42 views
22

我有一個通用的關係的模型:如何從Django模型獲取應用程序?

TrackedItem --- genericrelation ---> any model 

我希望能夠得到一般,從最初的模型,跟蹤項目。

我應該可以在任何模型上進行修改而不用修改它。

爲此,我需要獲取內容類型和對象ID。獲取對象ID很容易,因爲我有模型實例,但獲取內容類型不是:ContentType.object.filter需要模型(僅爲content_object.__class__.__name__)和app_label。

我不知道如何以可靠的方式獲取模型所在的應用程序。

現在我做app = content_object.__module__.split(".")[0],但它不適用於django contrib應用程序。

回答

28

您不需要獲取應用程序或模型剛拿到的contentType - 有做到這一點方便的方法:

ContentType.objects.get_for_model(myobject) 

儘管名稱,它適用於這兩種模型類和實例。

+3

這是比使用_meta更好的解決方案。 – Wogan 2010-04-30 06:47:48

+8

是嗎?這不是命中數據庫嗎? – meshy 2014-11-03 16:44:01

+1

@meshy yes但django ContentType在其管理器上使用緩存,因此它只在每個模型中查詢一次。 – dalore 2016-03-06 11:05:18

75

app_label可作爲任何模型的_meta屬性的屬性。

from django.contrib.auth.models import User 
print User._meta.app_label 
# The object name is also available 
print User._meta.object_name 
0

您可以使用內置的ContentType的

from django.contrib.contenttypes.models import ContentType 
from django.contrib.auth.models import User 

user_obj = User.objects.create() 
obj_content_type = ContentType.objects.get_for_model(user_obj) 

print(obj_content_type.app_label) 
# u'auth' 
print(obj_content_type.model) 
# u'user' 

這是一個更好的方法方面使用的是被定義爲私人的_meta性能得到你的對象既app_labelmodel

相關問題