34đ
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.
95đ
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 insyncdb
and remove them as part of areset
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 whenmanaged
isFalse
. All other aspects of model handling are exactly the same as normal.
- [Django]-How do I access the request object or any other variable in a form's clean() method?
- [Django]-How can I handle Exceptions raised by dango-social-auth?
- [Django]-Django Form File Field disappears on form error
14đ
I just implemented a model using a view with postgres 9.4 and django 1.8.
I created custom migration classes like this:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('myapp', '0002_previousdependency'),
]
sql = """
create VIEW myapp_myview as
select your view here
"""
operations = [
migrations.RunSQL("drop view if exists myapp_myview;"),
migrations.RunSQL(sql)
]
I wrote the model as I normally would. It works for my purposes.
Noteâ When I ran makemigrations a new migration file was created for the model, which I manually deleted.
Full disclosure- my view is read only because I am using a view derived from a jsonb data type and have not written an ON UPDATE INSTEAD rule.
- [Django]-Django: Calculate the Sum of the column values through query
- [Django]-Django: Create fixtures without specifying a primary key?
- [Django]-Django : How can I find a list of models that the ORM knows?
3đ
Weâve done this quite extensively in our applications with MySQL to work around the single database limitation of Django. Our application has a couple of databases living in a single MySQL instance. We can achieve cross-database model joins this way as long as we have created views for each table in the âcurrentâ database.
As far as inserts/updates into views go, with our use cases, a view is basically a âselect * from [db.table];â. In other words, we donât do any complex joins or filtering so insert/updates trigger from save() work just fine. If your use case requires such complex joins or extensive filtering, I suspect you wonât have any problems for read-only scenarios, but may run into insert/update issues. I think there are some underlying constraints in MySQL that prevent you from updating into views that cross tables, have complex filters, etc.
Anyway, your mileage may vary if you are using a RDBMS other than MySQL, but Django doesnât really care if its sitting on top of a physical table or view. Itâs going to be the RDBMS that determines whether it actually functions as you expect. As a previous commenter noted, youâll likely be throwing syncdb out the window, although we successfully worked around it with a post-syncdb signal that drops the physical table created by Django and runs our âcreate viewâŠâ command. However, the post-syncdb signal is a bit esoteric in the way it gets triggered, so caveat emptor there as well.
EDIT: Of course by âpost-syncdb signalâ I mean âpost-syncdb listenerâ
- [Django]-HTML â How to do a Confirmation popup to a Submit button and then send the request?
- [Django]-Is Django for the frontend or backend?
- [Django]-Django custom management commands: AttributeError: 'module' object has no attribute 'Command'
3đ
From Django Official Documentation, you could call the view like this:
#import library
from django.db import connection
#Create the cursor
cursor = connection.cursor()
#Write the SQL code
sql_string = 'SELECT * FROM myview'
#Execute the SQL
cursor.execute(sql_string)
result = cursor.fetchall()
Hope it helps đ
- [Django]-How can I create a deep clone of a DB object in Django?
- [Django]-Additional field while serializing django rest framework
- [Django]-Set Django IntegerField by choices=⊠name