Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django content-type : how do I get an object?

Tags:

django

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.

like image 914
interstar Avatar asked Aug 03 '09 08:08

interstar


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 django_ content_ type?

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.

How do you define an object in 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.

What is a content type model?

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.


1 Answers

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)
like image 93
Wogan Avatar answered Oct 03 '22 21:10

Wogan