hao*_*ike 0 python django graph python-2.7
我正在尝试使用 Python 2.7 和 Django 1.5 制作一个简单的天气 JSON API。
我的 WeatherData 模型如下所示:
class WeatherData(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
temp_f = models.DecimalField()
Run Code Online (Sandbox Code Playgroud)
在我看来,我想将created_atDjango 存储的日期时间对象转换为 UTC 秒。(我知道会有时区问题。)
我已经知道如何将日期时间对象(名为MYTIME)转换为秒:
import time
time.mktime(MYTIME.timetuple())
Run Code Online (Sandbox Code Playgroud)
但是,当我定义时,queryset = WeatherData.objects.all()我无法找到一种方法来将这些日期时间对象即时转换为 UTC 秒,同时维护查询集对象。简而言之,我想在模板中渲染之前修改视图中返回的查询集。
我是使用 Django 和 MySQL 的新手,但我想有一种方法可以做到这一点。
注意:我使用的是TastyPie,所以我无法直接访问模板文件。我在 ModelResource 类中指定查询集字段:
class WeatherResource(ModelResource):
class Meta:
queryset = WeatherData.objects.all()
fields = ['created_at' 'temp_f']
Run Code Online (Sandbox Code Playgroud)
我在这里先向您的帮助表示感谢!
您不必修改它,只需向WeatherData执行此操作的类添加一个方法,并为查询集中的每个对象调用模板中的方法:
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())
Run Code Online (Sandbox Code Playgroud)
并在您的模板中执行以下操作:
{% for data in deatherdata %}
data.created_at_utc
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我希望它有帮助!