Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Contenttypes used for in Django?

Tags:

django

Can you explain Django contenttypes at a very basic level?

What is their purpose?

like image 808
Amy Obrian Avatar asked Dec 17 '13 14:12

Amy Obrian


1 Answers

ContentType is just a model and table in the database that contains information about all the other tables/models in your django application.

Postgres table:

=> \d django_content_type;

  Column   |          Type          |                           Modifiers
-----------+------------------------+-----------------------------------------
 id        | integer                | not null ...
 name      | character varying(100) | not null
 app_label | character varying(100) | not null
 model     | character varying(100) | not null

Data in postgres:

=> SELECT * from django_content_type;

 id |         name          |     app_label     |        model        
----+-----------------------+-------------------+---------------------
  1 | permission            | auth              | permission
  2 | group                 | auth              | group
  3 | user                  | auth              | user
  4 | auth user groups      | auth              | authusergroups
...

For example, if you want to build a custom admin in your application, then to get list of tables you can use the ContentType model:

>>> from django.contrib.contenttypes.models import ContentType
>>> tables = ContentType.objects.filter(app_label="my_app")

Check the django admin source code for use cases. ContentTypes is actively used there.

like image 132
ndpu Avatar answered Sep 26 '22 16:09

ndpu