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

spence91 picture spence91 · Feb 3, 2009 · Viewed 37.9k times · Source

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:

  • manage.py syncdb will not work anymore
  • the view need the same thing at the start of its name as all the other models(tables) e.g if your app is called "thing" then your view will need to be called thing_$viewname

Answer

drdaeman picture drdaeman · Aug 15, 2009

Just an update for those who'll encounter this question (from Google or whatever else)...

Currently Django has a simple "proper way" to define model without managing database tables:

Options.managed

Defaults to True, meaning Django will create the appropriate database tables in syncdb and remove them as part of a reset management command. That is, Django manages the database tables' lifecycles.

If False, no database table creation or deletion operations will be performed for this model. This is useful if the model represents an existing table or a database view that has been created by some other means. This is the only difference when managed is False. All other aspects of model handling are exactly the same as normal.