How to get the app a Django model is from?

后端 未结 3 1979
既然无缘
既然无缘 2021-01-01 09:47

I have a model with a generic relation:

TrackedItem --- genericrelation ---> any model

I would like to be able to generically get, from

3条回答
  •  失恋的感觉
    2021-01-01 10:13

    You can get both app_label and model from your object using the built-in ContentType class:

    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'
    

    This is better approach respect of using the _meta properties that are defined for private purposes.

提交回复
热议问题