martingrant
martingrant

Reputation: 174

How can I store time based data in a Django model?

I am building a web application in Django. I have a system that will send a signal every minute to the application of how many people are in a building. I then want to be able to acess the data of a building (model) to e.g. display it in a graph (amount of people in the building during the course of an hour), or look up how many people there were e.g. at 5.30pm last wednesday.

How can I build this into a model where I can look up data based on date/time?

Thanks.

Upvotes: 0

Views: 2321

Answers (1)

tdsymonds
tdsymonds

Reputation: 1709

Your question is really vague, so it's hard to give a detailed response, but you could always try something along the lines of this:

# models.py
class BuildingCount(models.Model):
    number_of_people = models.IntegerField()
    datetime_stamp = models.DateTimeField(auto_now_add=True)

Then the signal creates the model:

b = BuildingCount(number_of_people=x)
b.save()

A datetime is a continuous field, so you're better off filtering between two datetimes then trying to get a record at a specific datetime. Here are a couple of examples:

from datetime import datetime, timedelta

# All counts in the past week
now = datetime.now()
one_week_ago = now - timedelta(days=7)
results = BuildingCount.objects.filter(datetime_stamp__range=(one_week_ago, now))
for result in results:
    print (result.number_of_people)

# Last Wed 5.30pm
# filter over a 2 min window and return the first record
result = BuildingCount.objects.filter(datetime_stamp__range=(datetime(2016,11,2,17,29), datetime(2016,11,2,17,31))).first()
print (result.number_of_people)

Hopefully this helps, alternatively if you provide more information I may be able to assist further...

Upvotes: 2

Related Questions