How can I obtain the model's name or the content type of a Django object?


Question

Let's say I am in the save code. How can I obtain the model's name or the content type of the object, and use it?

from django.db import models

class Foo(models.Model):
    ...
    def save(self):
        I am here....I want to obtain the model_name or the content type of the object

This code works, but I have to know the model_name:

import django.db.models
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get(model=model_name)
model = content_type.model_class()
1
38
2/1/2011 1:46:40 PM

Accepted Answer

You can get the model name from the object like this:

self.__class__.__name__

If you prefer the content type, you should be able to get that like this:

ContentType.objects.get_for_model(self)
63
2/1/2011 2:16:01 PM

The method get_for_model does some fancy stuff, but there are some cases when it's better to not use that fancy stuff. In particular, say you wanted to filter a model that linked to ContentType, maybe via a generic foreign key?? The question here was what to use for model_name in:

content_type = ContentType.objects.get(model=model_name)

Use Foo._meta.model_name, or if you have a Foo object, then obj._meta.model_name is what you're looking for. Then, you can do things like

Bar.objects.filter(content_type__model=Foo._meta.model_name)

This is an efficient way to filter the Bar table to return you objects which link to the Foo content type via a field named content_type.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon