django-db-views


Namedjango-db-views JSON
Version 0.1.6 PyPI version JSON
download
home_pagehttps://github.com/BezBartek/django-db-views
SummaryHandle 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
upload_time2023-12-03 00:29:08
maintainer
docs_urlNone
authorBartłomiej Nowak and Mariusz Okulanis
requires_python
licenseMIT
keywords views database views django database perspective view migrations database table function django materialized views
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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.8 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": "https://github.com/BezBartek/django-db-views",
    "name": "django-db-views",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "views,database views,django,database perspective,view migrations,database table function,django materialized views",
    "author": "Bart\u0142omiej Nowak and Mariusz Okulanis",
    "author_email": "n.bartek3762@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/32/5e/d65e2f5ecbfeb273f5205657bd9f92a38c92b525cd212f507523ba2a742d/django-db-views-0.1.6.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.8 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",
    "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.6",
    "project_urls": {
        "Homepage": "https://github.com/BezBartek/django-db-views"
    },
    "split_keywords": [
        "views",
        "database views",
        "django",
        "database perspective",
        "view migrations",
        "database table function",
        "django materialized views"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3543af3f4652f8e64e0360c296a90fba285ad577957d1097a2599a5efe8f5c30",
                "md5": "1ad9f466e7c17680ef0c3ea1549329ef",
                "sha256": "1ae8a6b389a2e8a7a2e246050ce7688780343bf4fd4f9622263b607ae27e5524"
            },
            "downloads": -1,
            "filename": "django_db_views-0.1.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "1ad9f466e7c17680ef0c3ea1549329ef",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 19966,
            "upload_time": "2023-12-03T00:29:06",
            "upload_time_iso_8601": "2023-12-03T00:29:06.725546Z",
            "url": "https://files.pythonhosted.org/packages/35/43/af3f4652f8e64e0360c296a90fba285ad577957d1097a2599a5efe8f5c30/django_db_views-0.1.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "325ed65e2f5ecbfeb273f5205657bd9f92a38c92b525cd212f507523ba2a742d",
                "md5": "742d728ab3e12a9dd9816b05d1df7d57",
                "sha256": "05718bb87c819323d577b294ee75f25807e5bb767793aa27f1ecc4c7ae073172"
            },
            "downloads": -1,
            "filename": "django-db-views-0.1.6.tar.gz",
            "has_sig": false,
            "md5_digest": "742d728ab3e12a9dd9816b05d1df7d57",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 16937,
            "upload_time": "2023-12-03T00:29:08",
            "upload_time_iso_8601": "2023-12-03T00:29:08.967460Z",
            "url": "https://files.pythonhosted.org/packages/32/5e/d65e2f5ecbfeb273f5205657bd9f92a38c92b525cd212f507523ba2a742d/django-db-views-0.1.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-12-03 00:29:08",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "BezBartek",
    "github_project": "django-db-views",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "tox": true,
    "lcname": "django-db-views"
}
        
Elapsed time: 0.22283s