Package: django-db-views
django-db-viewsDjango Versions2.2 to 4.2+Python Versions3.8 to 3.11How to install?pip install django-db-viewsWhat we offerDatabase viewsMaterialized viewsviews schema migrationsindexing for materialized views (future)database table function (future)How to use?adddjango_db_viewstoINSTALLED_APPSusemakeviewmigrationscommand to create migrations for view modelsHow to create view in your database?To create your view use DBView class, remember to set view definition attribute.fromdjango.dbimportmodelsfromdjango_db_views.db_viewimportDBViewclassVirtualCard(models.Model):...classBalance(DBView):virtual_card=models.ForeignKey(VirtualCard,# VirtualCard is a regular Django model.on_delete=models.DO_NOTHING,related_name='virtual_cards')total_discount=models.DecimalField(max_digits=12,decimal_places=2)total_returns=models.DecimalField(max_digits=12,decimal_places=2)balance=models.DecimalField(max_digits=12,decimal_places=2)view_definition="""SELECTrow_number() over () as id,  # Django requires column called idvirtual_card.id as virtual_card_id,sum(...) as total_discount,..."""classMeta:managed=False# Managed must be set to False!db_table='virtual_card_balance'The view definition can be:str/dictor a callable which returnsstr/dict.Callable view definition examples:fromdjango_db_views.db_viewimportDBViewlclassExampleView(DBView):@staticmethoddefview_definition():#  Note for MySQL users:#    In the case of MySQL you might have to use:#    connection.cursor().mogrify(*queryset.query.sql_with_params()).decode() instead of str method to get valid sql statement from Query.returnstr(SomeModel.objects.all().query)# ORview_definition=lambda:str(SomeModel.objects.all().query)classMeta:managed=Falsedb_table='example_view'using callable allow you to write view definition using ORM.Ensure that you includemanaged = Falsein the DBView model's Meta class to prevent Django creating it's own migration.How view migrations work?DBView working as regular django model. You can use it in any query.It's using Django code, view-migrations looks like regular migrations.It relies ondb_tablenames.makeviewmigrationscommand finds previous migration for view.if there is no such migration then script create a new migrationif previous migration exists but no change inview_definitionis detected nothing is doneif previous migration exists, then script will use previousview_definitionfor backward operation, and creates new migration.when run it will check if the current default engine definined in django.settings is the same engine the view was defined withMultidatabase supportYoy can define view_definition as
a dict for multiple engine types.If you do not pass in an engine and have a str or callable the
engine will be defaulted to the default database defined in django.It respects --database flag in the migrate command,
So you are able to define a specific view definitions for specific databases using the engine key.
If the key do not match your current database, view migration will be skipped.Also, feature becomes useful if you use a different engine for local / dev / staging / production.Example dict view definition:view_definition={"django.db.backends.sqlite3":"""SELECTrow_number() over () as id,q.id as question_id,count(*) as total_choicesFROM question qJOIN choice c on c.question_id = q.idGROUP BY q.id""","django.db.backends.postgresql":"""SELECTrow_number() over () as id,q.id as question_id,count(*) as total_choicesFROM question qJOIN choice c on c.question_id = q.idGROUP BY q.id""",}Materialized ViewsJust inherit fromDBMaterializedViewinstead of regularDBViewMaterialzied View provide an extra class method to refresh view calledrefreshNotesPlease use the newest version. version 0.1.0 has backward
incompatibility which is solved in version 0.1.1 and higher.