Reputation: 78
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.
Upvotes: 2
Views: 945
Reputation: 198
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)
Upvotes: 3