Using django-extensions to visualize the database diagram in django application

Yathomasi
2 min readJul 12, 2018

--

Drawing a database diagram for your django application can be a lot easier than starting a new drawing app or online sites. This can be achieved by using django-extensions . Django Extensions is a collection of custom extensions for the Django Framework. Among them we will use graph models to get the output of database design in png image format or dot format.

Search python-pygraphviz package for your OS and install it. Here is for Ubuntu 18.04.

$ sudo apt install python-pygraphviz

For Windows/Ubuntu integration you may need

$ sudo apt install pkg-config 

Now in your python environment (maybe some virtual environment)

$ pip install django-extensions pygraphviz

and add django-extensions to the installed apps of your django settings.

INSTALLED_APPS = [ 
...
'django_extensions',
]
#ALERT while copying: inverted comma in medium is different

Usage Examples:

#To group all the application and output into PNG file
$ python manage.py graph_models -a -g -o imagefile_name.png
#Include only some applications
$ python manage.py graph_models app1 app2 -o app1_app2.png
#Include only some specific models
$ python manage.py graph_models -a -I Foo,Bar -o foo_bar.png
#OR exclude certain models
$ python manage.py graph_models -a X Foo,Bar -o no_foo_bar.png

If there is problem with pygraphviz ,another method would be to use pydot which can be used to create dot files.

$ pip install pydot pyparsing==1.5.7 #use this specific version

Instead of giving output by -o image_name.png ,we can the catch the STDOUT given in a dot file for the same above examples

$ python manage.py graph_models -a > dotfile.dot$ python manage.py graph_models app1 app2 > fire_me.dot$ python manage.py graph_models -a -I Foo,Bar > something.dot$ python manage.py graph_models -a X Foo,Bar > nofoobar.dot

these dot file can be edited using this GraphvizOnline tool. You can find the nodes by the names and vertices in the relations section and tweak littlebit and get in the format you like(svg,png and many more).

Also the django-extensions is collections of extensions and this can come handy for many other purposes.

Generate (and view) a graphviz graph of app models:

$ python manage.py graph_models -a -o myapp_models.png

Produce a tab-separated list of (url_pattern, view_function, name) tuples for a project:

$ python manage.py show_urls

Check templates for rendering errors:

$ python manage.py validate_templates

Run the enhanced django shell:(you can directly start using models)

$ python manage.py shell_plus

Run the enhanced django runserver, (requires Werkzeug install):
This one is a cool debugger where you can use shell from browsers.

$ python manage.py runserver_plus

Finally. Thanks for reading ❤❤❤

--

--