user2959723 user2959723 - 5 months ago 13
Python Question

How to update django model objects if no update has happened over time(say 10 seconds)

In my use case, I'll keep getting data from different devices for every 10 seconds when they are Active (active=True)

When ever I receive data I'll update particular django object(database). But I'll never come to know if any device is inactive.

It's clear that, if I'm not getting data for every 10 seconds I should mark that object to active = False

In my database, almost 100k records exists and couldn't perform cron or any script for all records to update.

Is there a way to mark active = False automatically if no update happened to any object over time in particular model


Do you actually need them marked as active?

How about simply recording the time of the latest update and make active a computed property?

from django.utils import timezone

# in your model, remove the "active" field
# and store the last update's datetime in a "last_update" field
# then...
def active(self):
    delta = - self.last_update
    return delta.total_seconds() < 10

That's how it's typically done if you don't need to run some code precisely when the state changes: you simply compute it based on data that does not need to be updated asynchronously.