Luis Medina
Luis Medina

Reputation: 555

Django DateTimeField query last hour

I'm trying to query the data from the last hour form a postgreSQL database,

this is the table model in Django:

class data(models.Model):
    fecha = models.TextField(db_column='Fecha', blank=True, null=True)  # Field name made lowercase.
    hora = models.TextField(db_column='Hora', blank=True, null=True)  # Field name made lowercase.
    lat = models.FloatField(blank=True, null=True)
    lng = models.FloatField(blank=True, null=True)
    tipo = models.BigIntegerField(db_column='Tipo', blank=True, null=True)  # Field name made lowercase.
    ka = models.FloatField(db_column='kA', blank=True, null=True)  # Field name made lowercase.
    error = models.FloatField(blank=True, null=True)
    tiempo = models.DateTimeField(db_column='Tiempo',primary_key=True, blank=True, null=False)  # Field name made lowercase.
    geom = models.PointField(blank=True, null=True)

and this is what I have in my views file:

from datetime import datetime, timedelta
time = datetime.now() - timedelta(hours=1)
def last_hour(request):  
    hour = serialize('geojson',data.objects.filter(tiempo__lt=time))
    return HttpResponse(hour, content_type='json')

I haven been luckly with the information of other posts. My Django version is 3.0.5 and the timezone data in postgreSQL is utc-5

Upvotes: 3

Views: 1199

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

If that is the last hour, then tiempo should be greater than the timestamp of an hour ago. You should also calculate that in the view function, since otherwise if you later query the view, it will always return data later than an hour before you started the web server:

from datetime import datetime, timedelta

def last_hour(request):
    time = datetime.now() - timedelta(hours=1)
    hour = serialize('geojson',data.objects.filter(tiempo__gte=time))
    return HttpResponse(hour, content_type='json')

Upvotes: 7

Related Questions