Django 1.8 inspectdb command doesn't see PostgreSQL views as per documentation

Question:

I have a Django 1.8 application with a PostgreSQL database. I run the django inspectdb from the command line to examine models for the views, but the views don’t show up in the model output.

Here’s the version output:

17:36 $ python well/manage.py --version
1.8.2

And here’s what psql sees:

dv
                List of relations
 Schema |             Name              | Type |  Owner  
--------+-------------------------------+------+---------
 public | hospitalizations_over_30_days | view | dwatson
 public | interval_30_days              | view | dwatson
(2 rows)

From the django 1.8.2 documentation:

New in Django 1.8:
A feature to inspect database views was added. In previous versions, only tables (not views) were inspected.

How can I get the PostgreSQL views to appear in the Django 1.8.2 inspectdb output?

Asked By: David Watson

||

Answers:

As of Django 1.10, you can simply name an individual view as a parameter to your inspectdb command:

python well/manage.py inspectdb hospitalizations_over_30_days

The default inspectdb will only output models.py for tables, but models for views can be generated individually by naming them.

In Django 2.1 and above, if you want inspectdb to generate models for all tables and views, use the inspectdb --include-views option, which I contributed to Django 2.1 as a result of this question!

python well/manage.py inspectdb --include-views

To generate models for both tables and views in Django 2.0 and below, you have to edit the Django source code. In Django 2.0, change line 57 in django/core/management/commands/inspectdb.py to:

tables_to_introspect = options['table'] or connection.introspection.table_names(cursor=cursor, include_views=True)

Beware that the generated models won’t have fields with primary_key=True set, you will need to add primary keys manually.

Answered By: Brendan Quinn

In recent releases, there is an option to include views by passing it to the command as follows (both tables and views will be inspected):

python manage.py inspectdb --include-views > my_models.py
Answered By: Ahmed

I’m a beginner,Not sure whether it add more value. Still As an extension to the answers.
Once we setup the settings.py,if we got multiple schemas and just need specific view.

python manage.py inspectdb --database [alias name for the database connection string in settings.py] --include-views [name of the view]>model.py

May be its helpful for beginners.

Answered By: AmalJose
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.