Periodically create/update a model based on another model's annotation
I have model
Foo that changes periodically (every week for simplicity). The corresponding API endpoint for this model only needs the annotation
foo_annotate. I want to be able to backtrack even if the period changes. My current setup works fine but I realized that if new entries are created in the database, I may run out of storage. So instead of doing that, I create a new model based on the computed value from
Here's what I have so far:
class FooManager(models.Manager): ... def get_queryset(self): return super(FooManager, self).get_queryset() \ .annotate(foo_annotate=Coalesce(models.Count("bar"), 0)) # Annotation is much more complex class Foo(models.Model): # Periodic model ... period = models.CharField(...) # Name of current period, unsure if DateField is better user = models.ForeignKey(User, ...) objects = FooManager() class Bar(models.Model): # Fields may change ... foo = models.ForeignKey(Foo, ...) class Baz(models.Model): # Model based on annotation period = ... foo_annotate = ???
If I understand you problem correctly, you should be able to utilize a pre_save or post_save signal. Signals in django are used to trigger events or alter data on certain events. Most commonly when a instance is saved or deleted.