0
votes

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!

1
Are you trying to modify the data solely for the purpose of rendering it in your template, or is it so you can then perform other operations (i.e. sorting, choosing a template dynamically, etc.)? If it's the former, you won't want to modify the queryset at all ... rather you'd use a template tag that would do the conversion at the time of rendering. If it's the latter, then there are several approaches you could try. Provide a bit more of the context to get some specific solutions. - jlmcdonald
It's just for rendering. Specifically, I need to serialize the datetime object into JSON. But since I'm using TastyPie, I don't have access to the template file. - hao_maike

1 Answers

5
votes

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!