With a model like below, I want to return the number of times an object was retrieved today
class Watched(Stamping): user = models.ForeignKey("User", null=True, blank=True, on_delete=models.CASCADE, default=None) count = models.PositiveIntegerField()
The Stamping
is another model with created_at
and updated_at
Below is the example of what I want to achieve
a = Watched.objects.filter("only_the_ones_retrieved_today") for b in a: return "b.count but only today's incremented values"
Advertisement
Answer
You can simply add a total_count
and a daily_count
column, then reset the daily_count
every day at midnight. For example:
class Watched(Stamping): ... total_count = models.PositiveIntegerField(default=0) daily_count = models.PositiveIntegerField(default=0) ...
Then increase both fields from your get_or_create()
handler.
You can then execute a piece of code every midnight that resets the daily_count
for all Watched
instances. I recommend you to write a custom django-admin command and run it via a cron job or similar:
Watched.objects.all().update(daily_count=0)