Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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
like image 560
spence91 Avatar asked Feb 03 '09 16:02

spence91


People also ask

Is Django models a database?

The basics: Each model is a Python class that subclasses django.db.models.Model . Each attribute of the model represents a database field. With all of this, Django gives you an automatically-generated database-access API; see Making queries.


1 Answers

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.

like image 58
drdaeman Avatar answered Sep 22 '22 14:09

drdaeman