开发者

Utility of managed=False option in Django models

In django models we have option named managed which can be set True or False

According to documentation the only difference this option makes is whether table will be managed by django or not. Is management by django or by us makes any difference?

Is there any pros开发者_如何学Python and cons of using one option rather than other?

I mean why would we opt for managed=False? Will it give some extra control or power which affects my code?


The main reason for using managed=False is if your model is backed by something like a database view, instead of a table - so you don't want Django to issue CREATE TABLE commands when you run syncdb.


Right from Django docs:

managed=False 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=False. All other aspects of model handling are exactly the same as normal


When ever we create the django model, the managed=True implicitly is true by default. As we know that when we run python manage.py makemigrations the migration file(which we can say a db view) is created in migration folder of the app and to apply that migration i.e creates the table in db or we can say schema.

So by managed=False, we restrict Django to create table(scheme, update the schema of the table) of that model or its fields specified in migration file.

Why we use its?

case1: Sometime we use two db for the project for example we have db1(default) and db2, so we don't want particular model to be create the schema or table in db1 so we can this or we can customize the db view.

case2. In django ORM, the db table is tied to django ORM model, It help tie a database view to bind with a django ORM model.

Can also go through the link:

We can add our raw sql for db view in migration file.

The raw sql in migration look like: In 0001_initial.py

from future import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.RunSQL(
CREATE OR REPLACE VIEW app_test AS 
    SELECT row_number() OVER () as id,
        ci.user_id,
        ci.company_id,

),
    ]

Above code is just for overview of the looking of the migration file, can go through above link for brief.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜