djangodjango-migrationssql-viewdjango-syncdb

Can I use a database view as a model in Django?


i'd like to use a view i've created in my database as the source for my django-view.

Is this possible, without using custom sql?

******13/02/09 UPDATE***********

Like many of the answers suggest, you can just make your own view in the database and then use it within the API by defining it in models.py.

some warning though:


Solution

  • Since Django 1.1, you can use Options.managed for that.

    For older versions, you can easily define a Model class for a view and use it like your other views. I just tested it using a Sqlite-based app and it seems to work fine. Just make sure to add a primary key field if your view's "primary key" column is not named 'id' and specify the view's name in the Meta options if your view is not called 'app_classname'.

    The only problem is that the "syncdb" command will raise an exception since Django will try to create the table. You can prevent that by defining the 'view models' in a separate Python file, different than models.py. This way, Django will not see them when introspecting models.py to determine the models to create for the app and therefor will not attempt to create the table.