hao_maike hao_maike - 3 months ago 9
Python Question

Django views: how to modify returned queryset before rendering in template?

I'm trying to make a simple weather JSON API with Python 2.7 and Django 1.5.

My WeatherData model looks like this:

class WeatherData(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
temp_f = models.DecimalField()


In my views, I want to convert the
created_at
datetime object stored by Django into UTC seconds.
(I understand there will be a timezone problem.)

I already know how to convert a datetime object (named
MYTIME
) to seconds:

import time
time.mktime(MYTIME.timetuple())


However, when I define the
queryset = WeatherData.objects.all()
I can't figure out a way to convert these datetime objects on-the-fly to UTC seconds while maintaining the queryset object. In short, I want to modify a returned queryset in the views before rendering in template.

I'm new to using Django and MySQL but I imagine there's a way to do this.

Note: I'm using TastyPie, so I don't have direct access to a template file. I specify the queryset fields in a ModelResource class:

class WeatherResource(ModelResource):
class Meta:
queryset = WeatherData.objects.all()
fields = ['created_at' 'temp_f']


Thanks for the help in advance!

Answer

You don't have to modify it, just add a method to the WeatherData class that do this and call the method within the template for each object in the query set:

import time
class WeatherData(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    temp_f = models.DecimalField()

    def created_at_utc(self):
        # whatever logic you need to do the conversion
        return time.mktime(self.created_at.timetuple())

and within your template do this:

{% for data in deatherdata %}
    data.created_at_utc
{% endfor %}

I hope it helps!

Comments