Skip to main content

autoupdated database fields for model methods

Project description

Build Status Coverage Status

django-computedfields

django-computedfields provides autoupdated database fields for model methods.

Tested with Django 1.10, 1.11 and 2.0 with Python 2.7, 3.5 and 3.6 (Django 2.0 is Python 3 only).

Example

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

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))
    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. With the method compute('fieldname') you can inspect the value that will be written, which is useful if you have pending changes:

>>> person = MyModel(forename='berty')
>>> person.computed_field             # empty since not saved yet
>>> person.compute('computed_field')  # outputs 'BERTY'
>>> person.save()
>>> person.computed_field             # outputs 'BERTY'

The computed decorator supports a depends keyword argument to indicate dependencies to other model fields. If set, the computed field gets automatically updated upon changes of the related fields:

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=['fk'])
    def computed_field(self):
        return self.name.upper() + self.fk.fieldname

Now changes to fk will now also update computed_field.

Documentation

The documentation can be found here.

TODO

  • optimize update querysets with select_related and prefetch_related

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Filename, size & hash SHA256 hash help File type Python version Upload date
django-computedfields-0.0.8.tar.gz (427.2 kB) Copy SHA256 hash SHA256 Source None Apr 2, 2018

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page