1
我在models.py
轉換爲本地時間Django的查詢集
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
在我settings.py
我有
TIME_ZONE = 'UTC'
USE_TZ = True
我想時代在特定的時區下面這個模型定義。 現在,如果我打電話給Blog.objects.all()
,它會以UTC
格式提供所有時間。但我希望用戶所在時區的時間。
我知道這裏有過濾器和標籤可用。但是,因爲我在做rest_framework
我想我需要能夠做到Queryset
。
任何幫助?
編輯:
我寫的查詢集這樣到目前爲止
from django.utils import timezone
from django.db import models
Blog.objects.annotate(
local_create_time = timezone.template_localtime(models.Expressionwrapper(models.F('created'), output_field=models.DateTimeField(), pytz.timezone('Europe/Madrid'))
)
它不將數據轉換爲Europe/Madrid
timzone。但將數據輸出到UTC
timzone。
所以我檢查了timzone.template_localtime(value, use_tz=None)
的定義。
對我來說use_tz行經tzinfo
對象,但value
是ExpressionWrapper(F(created))
好,我想我UTC格式轉換爲本地TIMEFORMAT用於查詢集中的所有模型實例。 –