ContentType.model_class()
Returns the model class represented by this ContentType
instance.
For example, we could look up the ContentType
for the User
model:
>>> from django.contrib.contenttypes.models import ContentType >>> ContentType.objects.get(app_label="auth", model="user") <ContentType: user>
And then use it to query for a particular User
, or to get access to the User
model class:
>>> user_type.model_class() <class 'django.contrib.auth.models.User'> >>> user_type.get_object_for_this_type(username='Guido') <User: Guido>
Together, get_object_for_this_type()
and model_class()
enable two extremely important use cases:
- Using these methods, you can write high-level generic code that performs queries on any installed model – instead of importing and using a single specific model class, you can pass an
app_label
andmodel
into aContentType
lookup at runtime, and then work with the model class or retrieve objects from it. - You can relate another model to
ContentType
as a way of tying instances of it to particular model classes, and use these methods to get access to those model classes.
Several of Django’s bundled applications make use of the latter technique. For example, the permissions system
in Django’s authentication framework uses a Permission
model with a foreign key to ContentType
; this lets Permission
represent concepts like “can add blog entry” or “can delete news story”.
Please login to continue.