2👍
It is said that premature optimization is the mother of all problems. You should start with the dumbest implementation (update it every time), and then measure and – if needed – replace it with something more efficient.
First of all, let’s put a method to update the last_active_at
field on Person
. That way, all the updating logic itself is concentrated here, and we can easily modify it later.
The signals are quite easy to use : it’s just about declaring a function and registering it as a receiver, and it will be ran each time the signal is emitted. See the documentation for the full explanation, but here is what it might look like :
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=RelatedModel)
def my_handler(sender, **kwargs):
# sender is the object being saved
person = # Person to be updated
person.update_activity()
As for the updating itself, start with the dumbest way to do it.
def update_activity(self):
self.last_active_at = now()
Then measure and decide if it’s a problem or not. If it’s a problem, some of the things you can do are :
- Check if the previous update is recent before updating again. Might be useless if a read to you database is not faster than a write. Not a problem if you use a cache.
- Write it down somewhere for a deferred process to update later. No need to be daily : if the problem is that you have 100 updates per seconds, you can just have a script update the database every 10 seconds, or every minutes. You can probably find a good performance/uptodatiness trade-off using this technique.
These are just some though based on what you proposed, but the right choice depends on the kind of figures you have. Determine what kind of load you’ll have, what kind of reaction time is needed for that field, and experiment.