MongoEngine/mongoengine

Proposal: `ComputedField` that computes a value based on a provided function

sbruens opened this issue · 1 comments

Many frameworks support something like a computed property (e.g. ndb's ComputedProperty), which is usually based on one or more pieces of the model's data.

I'm proposing a new ComputedField whose value is computed based on some user-supplied function, but have the value written to the database so it can be used like any other stored value. A common use case is to keep a field in sync with several other fields, but it could be any function that generates a value. I believe the SequenceField is already a variant of this type of field.

class Person(Document):
  name = StringField()
  name_lower = ComputedField(lambda self: self.name.lower())

  @ComputedField
  def name_upper(self):
    return self.name.upper()

I could start on an implementation, but curious to hear thoughts.

This is a rabbit hole that I'd prefer not to explore as users will have expectations to have this field in-sync also when you use e.g Person.objects.update(name="some_new_value") and this would be impossible to satisfy in a simple way.

What you want can be achieved with clean() (https://docs.mongoengine.org/guide/validation.html#custom-validation), signals or get/setters/@Property and at least the user is in charge of dealing with the consequences of such design.