简体   繁体   中英

Return the number of times my django model object was retrieved today

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"

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM