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()
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With