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