Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the app a Django model is from?

Tags:

django

model

I have a model with a generic relation:

TrackedItem --- genericrelation ---> any model

I would like to be able to generically get, from the initial model, the tracked item.

I should be able to do it on any model without modifying it.

To do that I need to get the content type and the object id. Getting the object id is easy since I have the model instance, but getting the content type is not: ContentType.object.filter requires the model (which is just content_object.__class__.__name__) and the app_label.

I have no idea of how to get in a reliable way the app in which a model is.

For now I do app = content_object.__module__.split(".")[0], but it doesn't work with django contrib apps.

like image 873
e-satis Avatar asked Apr 30 '10 06:04

e-satis


People also ask

Where can I find app name in Django?

You can get application name from model: Book. _meta. app_label .

How do I find model in Django?

In Django 1.7+ it is better to use get_model() on the Django app registry, which is available via django. apps. apps. get_model(model_name) .

What is an app in Django?

A Django app is a small library representing a discrete part of a larger project. For example, our blog web application might have an app for posts , one for static pages like an About page called pages , and another app called payments to charge logged-in subscribers.

Where is Installed_apps Django?

In your settings.py file, you will find INSTALLED_APPS. Apps listed in INSTALLED_APPS are provided by Django for the developer's comfort.


3 Answers

The app_label is available as an attribute on the _meta attribute of any model.

from django.contrib.auth.models import User
print User._meta.app_label
# The object name is also available
print User._meta.object_name
like image 169
Wogan Avatar answered Oct 04 '22 15:10

Wogan


You don't need to get the app or model just to get the contenttype - there's a handy method to do just that:

from django.contrib.contenttypes.models import ContentType

ContentType.objects.get_for_model(myobject)

Despite the name, it works for both model classes and instances.

like image 33
Daniel Roseman Avatar answered Oct 04 '22 13:10

Daniel Roseman


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.

like image 39
Dos Avatar answered Oct 04 '22 13:10

Dos