I'd like to defer calculating a value for a particular field until the
value is required.
Suppose I have these models:
class Fruit(models.Model):
# various fields
class FruitBasket(models.Model):
fruit = models.ManyToManyField(Fruit)
I'd like to add a "most_nutritious" field to FruitBasket that is a
ForeignKey to a fruit object, which will represent the most nutritious
fruit in the basket. But determining which fruit is the most
nutritious is expensive, so I'd like to only set a value for this if
it's required. But if I do compute a value, I want to store it in the
database so that I don't have to re-compute every time.
Ideally, I'd like to do something like this:
most_nutritious = models.LazyField(default=None,
compute=some_callable)
Whenever a FruitBasket is loaded, if the raw value of
"most_nutritious" is None, some validator computes the identity of the
most nutritious fruit, saves it, and pretends the value was always
there. If it's not None, the validator just returns the value
unmodified.
I think I'd know how to implement this if calculating the final value
did not depend on the value of other columns. My problem is that
to_python methods & co. are not (to my knowledge) given access to the
model instance being loaded/saved -- just the column value.)
Any thoughts?
Thanks!
Ori
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
No comments:
Post a Comment