If I have a django content_type reference (the id of the model.class and the id of the object), what's the best way to get the actual object itself?
Sounds trivial but I can't actually see an example anywhere.
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.
Content types are Django's way of identifying database tables. Every Database table is represented as a row in the content type table which is created and maintained by Django.
To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.
contenttypes is a Django app that can track all of the models installed in our Django-powered project, providing a high-level, generic interface for working with our models. If we check in settings INSTALLED_APPS we can see, that django. contrib. contenttypes is readily present.
From memory, it is something like this:
from django.contrib.contenttypes.models import ContentType
ct = ContentType.objects.get_for_id(content_type)
obj = ct.get_object_for_this_type(pk=object_id)
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