-
Notifications
You must be signed in to change notification settings - Fork 15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support disabling compute on create #157
Comments
Yupp, this has been the case forever for m2m relations. It used to work for fk backrelations until django unified the "error behavioral pattern" for relations on newly created instances around v4. (Also see the 2nd note in the docs here: https://django-computedfields.readthedocs.io/en/latest/manual.html#automatic-updates) In general I like the idea to provide a fallback value for those cases and using But before proceeding, I think there are a few catches we should try to address:
|
Most of my computed fields are cached counts or booleans, usually defaulting to
0
orFalse
. These fields often depend on related objects, so if you try something likeself.thing.count()
before the model is saved, it crashes because the relation doesn’t exist yet.To handle this, I’ve been adding
if instance._state.adding
checks in my compute functions. While this works, it’s repetitive and clutters the code.I created a wrapper that skips computing the value for new records unless explicitly requested. This simplifies compute functions, letting me avoid manual checks for new instances. For example, instead of writing:
I can just write:
The default value is already handled by the field itself, e.g.,
models.PositiveIntegerField(default=0)
.Here’s the wrapper:
Rethinking the default
Initially, I made
immediate=False
the default, as most of my computed fields don’t need immediate computation (only 2 out of 7 do). However, after reflecting on how technologies like Vue behave, I realized that watch functions (not computed properties) are the ones that defer execution by default. Computed properties, on the other hand, run immediately when accessed.With that in mind, it might make more sense for the default behavior to be
immediate=True
—so that computed fields run immediately, consistent with existing behavior and developer expectations. You’d then opt out of immediate execution when necessary, making it an explicit choice rather than the default.Next steps
I’m happy to open a pull request if there’s interest. I could also make the default for immediate configurable as a project-wide setting, allowing for compatibility with existing behavior while letting teams customize it for their needs.
The text was updated successfully, but these errors were encountered: