简体   繁体   中英

How to get last object in each hour over last 7 days in Django using DatetimeField column?

I have been doing a task of filtering values from a table called 'Feeds',

The row gets inserted every 10 mins into the system. ie. 6 rows every hour I am storing its datetime in a column called timestamp.

I want to filter last row of each such hour of past 7 days.

Here is my code.

class Feeds(models.Model):
    value = models.FloatField()
    timestamp = models.DateTimeField(auto_now_add=True)`

Please Help to solve this. Thank you.

Get the objects of last 7 days, then get objects from every hour and find the object with the greatest datetime value, exclude others.

d = datetime.now() - timedelta(days=7)
feeds = Feeds.objects.filter(timestamp__gte=d)
d = d.replace(minute=0, second=0, microsecond=0)
while d <= datetime.now():
    temp = feeds.filter(timestamp__range=(d, d + timedelta(hours=1)))
    if temp:
        temp = temp.exclude(timestamp=temp.all().order_by('-timestamp')[0].timestamp)
        for t in temp:
            feeds = feeds.exclude(timestamp=t.timestamp)            
    d += timedelta(hours=1)

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