django-computedfields


Namedjango-computedfields JSON
Version 0.2.4 PyPI version JSON
download
home_pagehttps://github.com/netzkolchose/django-computedfields
Summaryautoupdated database fields for model methods
upload_time2023-10-31 17:52:07
maintainer
docs_urlNone
authornetzkolchose
requires_python
licenseMIT
keywords django method decorator autoupdate persistent field
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            [![build](https://github.com/netzkolchose/django-computedfields/actions/workflows/build.yml/badge.svg)](https://github.com/netzkolchose/django-computedfields/actions/workflows/build.yml)
[![Coverage Status](https://coveralls.io/repos/github/netzkolchose/django-computedfields/badge.svg?branch=master)](https://coveralls.io/github/netzkolchose/django-computedfields?branch=master)


### django-computedfields

django-computedfields provides autoupdated database fields
for model methods.

Tested with Django 3.2 and 4.2 (Python 3.7 to 3.10).


#### Example

Just derive your model from `ComputedFieldsModel` and place
the `@computed` decorator at a method:

```python
from django.db import models
from computedfields.models import ComputedFieldsModel, computed

class MyModel(ComputedFieldsModel):
    name = models.CharField(max_length=32)

    @computed(models.CharField(max_length=32), depends=[('self', ['name'])])
    def computed_field(self):
        return self.name.upper()
```

`computed_field` will be turned into a real database field
and can be accessed and searched like any other database field.
During saving the associated method gets called and it’s result
written to the database.


#### How to recalculate without saving the model record

If you need to recalculate the computed field but without saving it, use
`from computedfields.models import compute`

```python
>>> from computedfields.models import compute
>>> person = MyModel.objects.get(id=1)  # this is to retrieve existing record
>>> person.computed_field               # outputs 'BERTY'
>>> person.name = 'nina'                # changing the dependent field `name` to nina
>>> compute(person, 'computed_field')   # outputs 'NINA'
>>> person.computed_field               # outputs 'BERTY' because the `person` is not yet saved
>>> person.save()                       # alters the database record for `name` and `computed_field`
>>> person.computed_field               # outputs 'NINA'
```

#### `depends` keyword

The  `depends` keyword argument can be used with any relation to indicate dependencies to fields on other models as well:

```python
from django.db import models
from computedfields.models import ComputedFieldsModel, computed

class MyModel(ComputedFieldsModel):
    name = models.CharField(max_length=32)
    fk = models.ForeignKey(SomeModel)

    @computed(
        models.CharField(max_length=32),
        depends=[
            ('self', ['name']),
            ('fk', ['fieldname'])
        ]
    )
    def computed_field(self):
        return self.name.upper() + self.fk.fieldname
```

Now changes to `self.name`, `fk` or `fk.fieldname` will update `computed_field`.


#### Alternative Syntax

Instead of using the `@computed` decorator with inline field definitions,
you can also use a more declarative syntax with `ComputedField`, example from above rewritten:

```python
from django.db import models
from computedfields.models import ComputedFieldsModel, ComputedField

def get_upper_string(inst):
    return inst.name.upper()

class MyModel(ComputedFieldsModel):
    name = models.CharField(max_length=32)
    computed_field = ComputedField(
        models.CharField(max_length=32),
        depends=[('self', ['name'])],
        compute=get_upper_string
    )
```


#### Documentation

The documentation can be found [here](https://django-computedfields.readthedocs.io/en/latest/index.html).


#### Changelog
- 0.2.4
    - performance improvement: use OR for simple multi dependency query construction
    - performance improvement: better queryset narrowing for M2M lookups
    - `ComputedField` for a more declarative code style added

- 0.2.3
    - performance improvement: use UNION for multi dependency query construction

- 0.2.2
    - Django 4.2 support
    - Use `model._base_manager` instead of `model.objects` to prevent using overridden `models.objects` with a custom manager

- 0.2.1
    - Django 4.1 support

- 0.2.0 - next beta release
    - new features:
        - better memory control for the update resolver via
          ``COMPUTEDFIELDS_QUERYSIZE`` or as argument on ``@computed``
        - update optimization - early update-tree exit
        - faster updates with ``COMPUTEDFIELDS_FASTUPDATE``
        - `checkdata` command
        - `showdependencies` command
        - typing support for computed fields

    - enhancements:
        - better `updatedata` command

    - removed features:
        - transitive reduction on intermodel graph (due to negative impact)
        - pickled resolver map (due to showing low benefit)
        - `update_dependent_multi` and `preupdate_dependent_multi`
          (due to showing low benefit and being a code nuisance)
        - Django 2.2 shims removed

    - bug fixes:
        - regression on proxy models fixed
        - sliced querset support for mysql fixed

- 0.1.7
    - add list type support for `update_fields` in signal handlers

- 0.1.6
    - maintenace version with CI test dependencies changes:
        - removed Python 3.6
        - removed Django 2.2
        - added Python 3.10
        - added Django 4.0
        - move dev environment to Python 3.10 and Django 3.2

      Note that Django 2.2 will keep working until real incompatible code changes occur.
      This may happen by any later release, thus treat 0.1.6 as last compatible version.

- 0.1.5
    - fix error on model instance cloning
- 0.1.4
    - Django 3.2 support
- 0.1.3
    - better multi table inheritance support and test cases
    - explicit docs for multi table inheritance
- 0.1.2
    - bugfix: o2o reverse name access
    - add docs about model inheritance support
- 0.1.1
    - bugfix: add missing migration
- 0.1.0
    - fix recursion on empty queryset
    - dependency expansion on M2M fields
    - `m2m_changed` handler with filtering on m2m fields
    - remove custom metaclass, introducing *Resolver* class
    - new decorator `@precomputed` for custom save methods
    - old *depends* syntax removed
    - docs update
- 0.0.23:
    - Bugfix: Fixing leaking computed fields in model inheritance.
- 0.0.22:
    - Automatic dependency expansion on reverse relations.
    - Example documentation.
- 0.0.21:
    - Bugfix: Fixing undefined _batchsize for pickled map usage.
- 0.0.20
    - Use `bulk_update` for computed field updates.
    - Allow custom update optimizations with *select_related* and *prefetch_related*.
    - Respect computed field MRO in `compute`.
    - Allow updates on local computed fields from `update_dependent` simplifying bulk actions on `ComputedFieldsModel`.
- 0.0.19
    - Better graph expansion on relation paths with support for *update_fields*.
- 0.0.18
    - New *depends* syntax deprecating the old one.
    - MRO of local computed field methods implemented.
- 0.0.17
    - Dropped Python 2.7 and Django 1.11 support.



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/netzkolchose/django-computedfields",
    "name": "django-computedfields",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "django,method,decorator,autoupdate,persistent,field",
    "author": "netzkolchose",
    "author_email": "j.breitbart@netzkolchose.de",
    "download_url": "https://files.pythonhosted.org/packages/07/02/0614ddaf41cdbb43d8499e2dc0eec105742bd0418eac1d213466ca4e109b/django-computedfields-0.2.4.tar.gz",
    "platform": null,
    "description": "[![build](https://github.com/netzkolchose/django-computedfields/actions/workflows/build.yml/badge.svg)](https://github.com/netzkolchose/django-computedfields/actions/workflows/build.yml)\n[![Coverage Status](https://coveralls.io/repos/github/netzkolchose/django-computedfields/badge.svg?branch=master)](https://coveralls.io/github/netzkolchose/django-computedfields?branch=master)\n\n\n### django-computedfields\n\ndjango-computedfields provides autoupdated database fields\nfor model methods.\n\nTested with Django 3.2 and 4.2 (Python 3.7 to 3.10).\n\n\n#### Example\n\nJust derive your model from `ComputedFieldsModel` and place\nthe `@computed` decorator at a method:\n\n```python\nfrom django.db import models\nfrom computedfields.models import ComputedFieldsModel, computed\n\nclass MyModel(ComputedFieldsModel):\n    name = models.CharField(max_length=32)\n\n    @computed(models.CharField(max_length=32), depends=[('self', ['name'])])\n    def computed_field(self):\n        return self.name.upper()\n```\n\n`computed_field` will be turned into a real database field\nand can be accessed and searched like any other database field.\nDuring saving the associated method gets called and it\u2019s result\nwritten to the database.\n\n\n#### How to recalculate without saving the model record\n\nIf you need to recalculate the computed field but without saving it, use\n`from computedfields.models import compute`\n\n```python\n>>> from computedfields.models import compute\n>>> person = MyModel.objects.get(id=1)  # this is to retrieve existing record\n>>> person.computed_field               # outputs 'BERTY'\n>>> person.name = 'nina'                # changing the dependent field `name` to nina\n>>> compute(person, 'computed_field')   # outputs 'NINA'\n>>> person.computed_field               # outputs 'BERTY' because the `person` is not yet saved\n>>> person.save()                       # alters the database record for `name` and `computed_field`\n>>> person.computed_field               # outputs 'NINA'\n```\n\n#### `depends` keyword\n\nThe  `depends` keyword argument can be used with any relation to indicate dependencies to fields on other models as well:\n\n```python\nfrom django.db import models\nfrom computedfields.models import ComputedFieldsModel, computed\n\nclass MyModel(ComputedFieldsModel):\n    name = models.CharField(max_length=32)\n    fk = models.ForeignKey(SomeModel)\n\n    @computed(\n        models.CharField(max_length=32),\n        depends=[\n            ('self', ['name']),\n            ('fk', ['fieldname'])\n        ]\n    )\n    def computed_field(self):\n        return self.name.upper() + self.fk.fieldname\n```\n\nNow changes to `self.name`, `fk` or `fk.fieldname` will update `computed_field`.\n\n\n#### Alternative Syntax\n\nInstead of using the `@computed` decorator with inline field definitions,\nyou can also use a more declarative syntax with `ComputedField`, example from above rewritten:\n\n```python\nfrom django.db import models\nfrom computedfields.models import ComputedFieldsModel, ComputedField\n\ndef get_upper_string(inst):\n    return inst.name.upper()\n\nclass MyModel(ComputedFieldsModel):\n    name = models.CharField(max_length=32)\n    computed_field = ComputedField(\n        models.CharField(max_length=32),\n        depends=[('self', ['name'])],\n        compute=get_upper_string\n    )\n```\n\n\n#### Documentation\n\nThe documentation can be found [here](https://django-computedfields.readthedocs.io/en/latest/index.html).\n\n\n#### Changelog\n- 0.2.4\n    - performance improvement: use OR for simple multi dependency query construction\n    - performance improvement: better queryset narrowing for M2M lookups\n    - `ComputedField` for a more declarative code style added\n\n- 0.2.3\n    - performance improvement: use UNION for multi dependency query construction\n\n- 0.2.2\n    - Django 4.2 support\n    - Use `model._base_manager` instead of `model.objects` to prevent using overridden `models.objects` with a custom manager\n\n- 0.2.1\n    - Django 4.1 support\n\n- 0.2.0 - next beta release\n    - new features:\n        - better memory control for the update resolver via\n          ``COMPUTEDFIELDS_QUERYSIZE`` or as argument on ``@computed``\n        - update optimization - early update-tree exit\n        - faster updates with ``COMPUTEDFIELDS_FASTUPDATE``\n        - `checkdata` command\n        - `showdependencies` command\n        - typing support for computed fields\n\n    - enhancements:\n        - better `updatedata` command\n\n    - removed features:\n        - transitive reduction on intermodel graph (due to negative impact)\n        - pickled resolver map (due to showing low benefit)\n        - `update_dependent_multi` and `preupdate_dependent_multi`\n          (due to showing low benefit and being a code nuisance)\n        - Django 2.2 shims removed\n\n    - bug fixes:\n        - regression on proxy models fixed\n        - sliced querset support for mysql fixed\n\n- 0.1.7\n    - add list type support for `update_fields` in signal handlers\n\n- 0.1.6\n    - maintenace version with CI test dependencies changes:\n        - removed Python 3.6\n        - removed Django 2.2\n        - added Python 3.10\n        - added Django 4.0\n        - move dev environment to Python 3.10 and Django 3.2\n\n      Note that Django 2.2 will keep working until real incompatible code changes occur.\n      This may happen by any later release, thus treat 0.1.6 as last compatible version.\n\n- 0.1.5\n    - fix error on model instance cloning\n- 0.1.4\n    - Django 3.2 support\n- 0.1.3\n    - better multi table inheritance support and test cases\n    - explicit docs for multi table inheritance\n- 0.1.2\n    - bugfix: o2o reverse name access\n    - add docs about model inheritance support\n- 0.1.1\n    - bugfix: add missing migration\n- 0.1.0\n    - fix recursion on empty queryset\n    - dependency expansion on M2M fields\n    - `m2m_changed` handler with filtering on m2m fields\n    - remove custom metaclass, introducing *Resolver* class\n    - new decorator `@precomputed` for custom save methods\n    - old *depends* syntax removed\n    - docs update\n- 0.0.23:\n    - Bugfix: Fixing leaking computed fields in model inheritance.\n- 0.0.22:\n    - Automatic dependency expansion on reverse relations.\n    - Example documentation.\n- 0.0.21:\n    - Bugfix: Fixing undefined _batchsize for pickled map usage.\n- 0.0.20\n    - Use `bulk_update` for computed field updates.\n    - Allow custom update optimizations with *select_related* and *prefetch_related*.\n    - Respect computed field MRO in `compute`.\n    - Allow updates on local computed fields from `update_dependent` simplifying bulk actions on `ComputedFieldsModel`.\n- 0.0.19\n    - Better graph expansion on relation paths with support for *update_fields*.\n- 0.0.18\n    - New *depends* syntax deprecating the old one.\n    - MRO of local computed field methods implemented.\n- 0.0.17\n    - Dropped Python 2.7 and Django 1.11 support.\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "autoupdated database fields for model methods",
    "version": "0.2.4",
    "project_urls": {
        "Download": "https://github.com/netzkolchose/django-computedfields/archive/0.2.3.tar.gz",
        "Homepage": "https://github.com/netzkolchose/django-computedfields"
    },
    "split_keywords": [
        "django",
        "method",
        "decorator",
        "autoupdate",
        "persistent",
        "field"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "07020614ddaf41cdbb43d8499e2dc0eec105742bd0418eac1d213466ca4e109b",
                "md5": "a754d294726bbf3778609a7ad0a1c52d",
                "sha256": "546a99afc7d2e9df3b1d29bdc1eaa4a6b003a75ad162f62e52dd89319c595692"
            },
            "downloads": -1,
            "filename": "django-computedfields-0.2.4.tar.gz",
            "has_sig": false,
            "md5_digest": "a754d294726bbf3778609a7ad0a1c52d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 476325,
            "upload_time": "2023-10-31T17:52:07",
            "upload_time_iso_8601": "2023-10-31T17:52:07.127209Z",
            "url": "https://files.pythonhosted.org/packages/07/02/0614ddaf41cdbb43d8499e2dc0eec105742bd0418eac1d213466ca4e109b/django-computedfields-0.2.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-31 17:52:07",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "netzkolchose",
    "github_project": "django-computedfields",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "django-computedfields"
}
        
Elapsed time: 0.13025s