42👍
✅
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.
119👍
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)
- [Django]-Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
- [Django]-Django: show a ManyToManyField in a template?
- [Django]-Parsing unicode input using python json.loads
9👍
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.
👤Dos
- [Django]-How to stop celery worker process
- [Django]-Django Multiple Authentication Backend for one project
- [Django]-On Heroku, is there danger in a Django syncdb / South migrate after the instance has already restarted with changed model code?
Source:stackexchange.com