Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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() 
like image 384
Seitaridis Avatar asked Feb 01 '11 13:02

Seitaridis


People also ask

How do I get content type in Django?

The contenttypes framework is included in the default INSTALLED_APPS list created by django-admin startproject , but if you've removed it or if you manually set up your INSTALLED_APPS list, you can enable it by adding 'django. contrib. contenttypes' to your INSTALLED_APPS setting.

What is __ Str__ in Django model?

The __str__() method is called whenever you call str() on an object. Django uses str(obj) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object.

How do you name a Django model?

Model styleField names should be all lowercase, using underscores instead of camelCase. The class Meta should appear after the fields are defined, with a single blank line separating the fields and the class definition.

Is there a list field for Django models?

Mine is simpler to implement, and you can pass a list, dict, or anything that can be converted into json. In Django 1.10 and above, there's a new ArrayField field you can use.


1 Answers

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:

from django.contrib.contenttypes.models import ContentType ContentType.objects.get_for_model(self) 
like image 192
gravelpot Avatar answered Sep 22 '22 17:09

gravelpot