# django-db-views
[![License](https://img.shields.io/:license-mit-blue.svg)](http://doge.mit-license.org)
[![PyPi](https://badge.fury.io/py/django-db-views.svg)](https://pypi.org/project/django-db-views/)
**Django Versions** 2.2 to 4.2+
**Python Versions** 3.9 to 3.11
### How to install?
- `pip install django-db-views`
### What we offer
- Database views
- Materialized views
- views schema migrations
- indexing for materialized views (future)
- database table function (future)
### How to use?
- add `django_db_views` to `INSTALLED_APPS`
- use `makeviewmigrations` command to create migrations for view models
### How to create view in your database?
- To create your view use DBView class, remember to set view definition attribute.
```python
from django.db import models
from django_db_views.db_view import DBView
class VirtualCard(models.Model):
...
class Balance(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 = """
SELECT
row_number() over () as id, # Django requires column called id
virtual_card.id as virtual_card_id,
sum(...) as total_discount,
...
"""
class Meta:
managed = False # Managed must be set to False!
db_table = 'virtual_card_balance'
```
- The view definition can be: **str/dict** or a callable which returns **str/dict**.
Callable view definition examples:
```python
from django_db_views.db_view import DBViewl
class ExampleView(DBView):
@staticmethod
def view_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.
return str(SomeModel.objects.all().query)
# OR
view_definition = lambda: str(SomeModel.objects.all().query)
class Meta:
managed = False
db_table = 'example_view'
```
using callable allow you to write view definition using ORM.
- Ensure that you include `managed = False` in 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 on `db_table` names.
- `makeviewmigrations` command finds previous migration for view.
- if there is no such migration then script create a new migration
- if previous migration exists but no change in `view_definition` is detected nothing is done
- if previous migration exists, then script will use previous `view_definition` for 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 with
### Multidatabase support
Yoy 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:
```python
view_definition = {
"django.db.backends.sqlite3": """
SELECT
row_number() over () as id,
q.id as question_id,
count(*) as total_choices
FROM question q
JOIN choice c on c.question_id = q.id
GROUP BY q.id
""",
"django.db.backends.postgresql": """
SELECT
row_number() over () as id,
q.id as question_id,
count(*) as total_choices
FROM question q
JOIN choice c on c.question_id = q.id
GROUP BY q.id
""",
}
```
### Materialized Views
Just inherit from `DBMaterializedView` instead of regular `DBView`
Materialzied View provide an extra class method to refresh view called `refresh`
### Notes
_Please use the newest version. version 0.1.0 has backward
incompatibility which is solved in version 0.1.1 and higher._
Raw data
{
"_id": null,
"home_page": null,
"name": "django-db-views",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": "Bart\u0142omiej Nowak <n.bartek3762@gmail.com>",
"keywords": "database perspective, database table function, database views, django, django materialized views, view migrations, views",
"author": "Mariusz Okulanis",
"author_email": "Bart\u0142omiej Nowak <n.bartek3762@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/89/6c/4d8e227c5c9a39c328a26fa7a4551807515b4c91847c267464d738233974/django_db_views-0.1.9.tar.gz",
"platform": null,
"description": "# django-db-views\n\n\n[![License](https://img.shields.io/:license-mit-blue.svg)](http://doge.mit-license.org) \n[![PyPi](https://badge.fury.io/py/django-db-views.svg)](https://pypi.org/project/django-db-views/) \n**Django Versions** 2.2 to 4.2+ \n**Python Versions** 3.9 to 3.11 \n\n\n### How to install?\n - `pip install django-db-views`\n\n### What we offer\n - Database views\n - Materialized views\n - views schema migrations \n - indexing for materialized views (future)\n - database table function (future)\n\n### How to use?\n - add `django_db_views` to `INSTALLED_APPS`\n - use `makeviewmigrations` command to create migrations for view models\n\n\n### How to create view in your database?\n\n- To create your view use DBView class, remember to set view definition attribute.\n\n\n ```python\n from django.db import models\n from django_db_views.db_view import DBView\n \n \n class VirtualCard(models.Model):\n ...\n \n \n class Balance(DBView):\n\n virtual_card = models.ForeignKey(\n VirtualCard, # VirtualCard is a regular Django model. \n on_delete=models.DO_NOTHING, related_name='virtual_cards'\n )\n total_discount = models.DecimalField(max_digits=12, decimal_places=2)\n total_returns = models.DecimalField(max_digits=12, decimal_places=2)\n balance = models.DecimalField(max_digits=12, decimal_places=2)\n \n view_definition = \"\"\"\n SELECT\n row_number() over () as id, # Django requires column called id\n virtual_card.id as virtual_card_id,\n sum(...) as total_discount,\n ...\n \"\"\"\n \n class Meta:\n managed = False # Managed must be set to False!\n db_table = 'virtual_card_balance'\n ```\n\n\n- The view definition can be: **str/dict** or a callable which returns **str/dict**. \n\n Callable view definition examples:\n\n ```python\n from django_db_views.db_view import DBViewl\n \n class ExampleView(DBView):\n @staticmethod\n def view_definition():\n # Note for MySQL users:\n # In the case of MySQL you might have to use: \n # connection.cursor().mogrify(*queryset.query.sql_with_params()).decode() instead of str method to get valid sql statement from Query.\n return str(SomeModel.objects.all().query) \n\n # OR\n view_definition = lambda: str(SomeModel.objects.all().query)\n class Meta:\n managed = False \n db_table = 'example_view'\n ```\n\n using callable allow you to write view definition using ORM.\n\n- Ensure that you include `managed = False` in the DBView model's Meta class to prevent Django creating it's own migration.\n\n### How view migrations work? \n - DBView working as regular django model. You can use it in any query. \n - It's using Django code, view-migrations looks like regular migrations. \n - It relies on `db_table` names. \n - `makeviewmigrations` command finds previous migration for view.\n - if there is no such migration then script create a new migration\n - if previous migration exists but no change in `view_definition` is detected nothing is done\n - if previous migration exists, then script will use previous `view_definition` for backward operation, and creates new migration.\n - when run it will check if the current default engine definined in django.settings is the same engine the view was defined with\n\n\n### Multidatabase support\nYoy can define view_definition as\na dict for multiple engine types.\n\nIf you do not pass in an engine and have a str or callable the\nengine will be defaulted to the default database defined in django.\n\nIt respects --database flag in the migrate command,\nSo you are able to define a specific view definitions for specific databases using the engine key.\nIf the key do not match your current database, view migration will be skipped.\n\nAlso, feature becomes useful if you use a different engine for local / dev / staging / production.\n\nExample dict view definition:\n\n```python\nview_definition = {\n \"django.db.backends.sqlite3\": \"\"\"\n SELECT\n row_number() over () as id,\n q.id as question_id,\n count(*) as total_choices\n FROM question q\n JOIN choice c on c.question_id = q.id\n GROUP BY q.id\n \"\"\",\n \"django.db.backends.postgresql\": \"\"\"\n SELECT\n row_number() over () as id,\n q.id as question_id,\n count(*) as total_choices\n FROM question q\n JOIN choice c on c.question_id = q.id\n GROUP BY q.id\n \"\"\",\n}\n```\n\n### Materialized Views\n\nJust inherit from `DBMaterializedView` instead of regular `DBView`\n\nMaterialzied View provide an extra class method to refresh view called `refresh`\n\n\n### Notes\n_Please use the newest version. version 0.1.0 has backward\nincompatibility which is solved in version 0.1.1 and higher._\n",
"bugtrack_url": null,
"license": "MIT License",
"summary": "Handle database views. Allow to create migrations for database views. View migrations using django code. They can be reversed. Changes in model view definition are detected automatically. Support almost all options as regular makemigrations command",
"version": "0.1.9",
"project_urls": {
"Changelog": "https://github.com/BezBartek/django-db-views/blob/master/CHANGELOG.md",
"Documentation": "https://github.com/BezBartek/django-db-views/blob/master/README.md",
"Homepage": "https://github.com/BezBartek/django-db-views",
"Issues": "https://github.com/BezBartek/django-db-views/issues",
"Repository": "https://github.com/BezBartek/django-db-views"
},
"split_keywords": [
"database perspective",
" database table function",
" database views",
" django",
" django materialized views",
" view migrations",
" views"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "3460415ebd63ef6d47c352c594d4de2480169616fcd63f5e86407a4637b75585",
"md5": "2601fea8222ef8df29125a42a1681bac",
"sha256": "54c1c5eeb94e9161938e7e78ae0515ab9808589d24319c4a3dfd8bb8d7a06c17"
},
"downloads": -1,
"filename": "django_db_views-0.1.9-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "2601fea8222ef8df29125a42a1681bac",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": null,
"size": 16838,
"upload_time": "2024-12-05T08:10:20",
"upload_time_iso_8601": "2024-12-05T08:10:20.173739Z",
"url": "https://files.pythonhosted.org/packages/34/60/415ebd63ef6d47c352c594d4de2480169616fcd63f5e86407a4637b75585/django_db_views-0.1.9-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "896c4d8e227c5c9a39c328a26fa7a4551807515b4c91847c267464d738233974",
"md5": "149bfd32b72e626a063a93c0de790fb7",
"sha256": "50d77790605d33e2c7ad8d550eb3dd9dd9fc57d775f70021ba637498e6944729"
},
"downloads": -1,
"filename": "django_db_views-0.1.9.tar.gz",
"has_sig": false,
"md5_digest": "149bfd32b72e626a063a93c0de790fb7",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 10899,
"upload_time": "2024-12-05T08:10:22",
"upload_time_iso_8601": "2024-12-05T08:10:22.173161Z",
"url": "https://files.pythonhosted.org/packages/89/6c/4d8e227c5c9a39c328a26fa7a4551807515b4c91847c267464d738233974/django_db_views-0.1.9.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-12-05 08:10:22",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "BezBartek",
"github_project": "django-db-views",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "django-db-views"
}