Edit: There seems to be some confusion about what I'm asking. That model is for the Postgres view that I created in migration 0009. I was under the impression that Django won't generate a migration for a model if it has the managed = False
option. However, it's still trying to create it.
Also, I'm using Django 1.8 with Python 3.4.
I'm having trouble creating a Django model for a Postgres view, using these links as a guide: drdaeman and eceppda's answer in Can I use a database view as a model in django. I also looked up the Options.managed entry in Django's API docs. However, even with this, it's creating a migration that adds a table for the view's model.
This is my code so far:
class RelevantModel(models.Model):
rebate_pool_total = models.OneToOneField('foo.VirtualTotal', null=True)
total = models.DecimalField(null=True, decimal_places=2, max_digits=32)
class VirtualTotal(models.Model):
relevant_model = models.ForeignKey('foo.RelevantModel')
total = models.DecimalField(null=True, decimal_places=2, max_digits=32)
class Meta:
managed = False
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('foo', '0008_previous_migration'),
]
sql = """
create VIEW foo_virtualtotal AS
SELECT rest of view...
"""
operations = [
migrations.RunSQL('DROP VIEW IF EXISTS foo_virtualtotal;'),
migrations.RunSQL(sql)
]
What am I doing wrong?
Django officially supports the following databases: PostgreSQL. MariaDB. MySQL.
The PostgreSQL views are created using the CREATE VIEW statement. The PostgreSQL views can be created from a single table, multiple tables, or another view. CREATE [TEMP | TEMPORARY] VIEW view_name AS SELECT column1, column2..... FROM table_name WHERE [condition];
Summary. Use the \dt or \dt+ command in psql to show tables in a specific database. Use the SELECT statement to query table information from the pg_catalog.
Django does create a migration for each newly added table in your app regardless of whether it's a managed model or not. However there is a very important and subtle difference when you use the managed=False
setting. The resultant migration is a dummy entry. It does not execute any SQL at all.
To confirm this add a new model that is unmanaged
class Dummy(models.Model):
something = models.IntegerField()
class Meta:
managed = False
now when you do makemigrations
followed by sqlimigrate *myapp* *migration_number*
you will see that it doesn't produce any sql.
If on the other hand, you do find that Django is trying to create a table for you, that usually means that you had the same model in existence earlier but at the time the model was managed. To confirm this, search your migrations
folder for VirtualTotal
which is the name of the model in question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With