Django model for a Postgres view

℡╲_俬逩灬. 提交于 2019-12-10 20:12:40

问题


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:

foo/models.py

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

foo/migrations/0009_add_foo_view.py

# -*- 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?


回答1:


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.



来源:https://stackoverflow.com/questions/38110785/django-model-for-a-postgres-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!