Package: django-computedfields
django-computedfieldsdjango-computedfields provides autoupdated database fields
for model methods.Tested with Django 3.2 and 4.2 (Python 3.8 to 3.11).ExampleJust derive your model fromComputedFieldsModeland place
the@computeddecorator at a method:fromdjango.dbimportmodelsfromcomputedfields.modelsimportComputedFieldsModel,computedclassMyModel(ComputedFieldsModel):name=models.CharField(max_length=32)@computed(models.CharField(max_length=32),depends=[('self',['name'])])defcomputed_field(self):returnself.name.upper()computed_fieldwill 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 recordIf you need to recalculate the computed field but without saving it, usefrom computedfields.models import compute>>>fromcomputedfields.modelsimportcompute>>>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'dependskeywordThedependskeyword argument can be used with any relation to indicate dependencies to fields on other models as well:fromdjango.dbimportmodelsfromcomputedfields.modelsimportComputedFieldsModel,computedclassMyModel(ComputedFieldsModel):name=models.CharField(max_length=32)fk=models.ForeignKey(SomeModel)@computed(models.CharField(max_length=32),depends=[('self',['name']),('fk',['fieldname'])])defcomputed_field(self):returnself.name.upper()+self.fk.fieldnameNow changes toself.name,fkorfk.fieldnamewill updatecomputed_field.Alternative SyntaxInstead of using the@computeddecorator with inline field definitions,
you can also use a more declarative syntax withComputedField, example from above rewritten:fromdjango.dbimportmodelsfromcomputedfields.modelsimportComputedFieldsModel,ComputedFielddefget_upper_string(inst):returninst.name.upper()classMyModel(ComputedFieldsModel):name=models.CharField(max_length=32)computed_field=ComputedField(models.CharField(max_length=32),depends=[('self',['name'])],compute=get_upper_string)DocumentationThe documentation can be foundhere.Changelog0.2.5Django 5.0 & Python 3.12 supportDjango 3.2 support dropped0.2.4performance improvement: use OR for simple multi dependency query constructionperformance improvement: better queryset narrowing for M2M lookupsComputedFieldfor a more declarative code style added0.2.3performance improvement: use UNION for multi dependency query construction0.2.2Django 4.2 supportUsemodel._base_managerinstead ofmodel.objectsto prevent using overriddenmodels.objectswith a custom manager0.2.1Django 4.1 support0.2.0 - next beta releasenew features:better memory control for the update resolver viaCOMPUTEDFIELDS_QUERYSIZEor as argument on@computedupdate optimization - early update-tree exitfaster updates withCOMPUTEDFIELDS_FASTUPDATEcheckdatacommandshowdependenciescommandtyping support for computed fieldsenhancements:betterupdatedatacommandremoved features:transitive reduction on intermodel graph (due to negative impact)pickled resolver map (due to showing low benefit)update_dependent_multiandpreupdate_dependent_multi(due to showing low benefit and being a code nuisance)Django 2.2 shims removedbug fixes:regression on proxy models fixedsliced querset support for mysql fixed0.1.7add list type support forupdate_fieldsin signal handlers0.1.6maintenace version with CI test dependencies changes:removed Python 3.6removed Django 2.2added Python 3.10added Django 4.0move dev environment to Python 3.10 and Django 3.2Note 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.5fix error on model instance cloning0.1.4Django 3.2 support0.1.3better multi table inheritance support and test casesexplicit docs for multi table inheritance0.1.2bugfix: o2o reverse name accessadd docs about model inheritance support0.1.1bugfix: add missing migration0.1.0fix recursion on empty querysetdependency expansion on M2M fieldsm2m_changedhandler with filtering on m2m fieldsremove custom metaclass, introducingResolverclassnew decorator@precomputedfor custom save methodsolddependssyntax removeddocs update0.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.20Usebulk_updatefor computed field updates.Allow custom update optimizations withselect_relatedandprefetch_related.Respect computed field MRO incompute.Allow updates on local computed fields fromupdate_dependentsimplifying bulk actions onComputedFieldsModel.0.0.19Better graph expansion on relation paths with support forupdate_fields.0.0.18Newdependssyntax deprecating the old one.MRO of local computed field methods implemented.0.0.17Dropped Python 2.7 and Django 1.11 support.