python - 为什么 Django Rest 框架中的时间不正确

标签 python django django-rest-framework datetime-format

为什么当我更新数据库中的条目时模型中的更新时间字段

updated = models.DateTimeField(auto_now=True)

根据我的设置文件中的时区正确更新,但当它出现在 Django Rest Framework 终端中时,它会向后移动 3 小时

以下代码适用于模型:

class hashtag(models.Model):
    tag = models.CharField(max_length=120)
    count = models.IntegerField(default=0,blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

以下代码适用于 DRF:

last_update = serializers.SerializerMethodField()
class Meta:
    model =  hashtag
    fields = [
        'id',
        'tag',     
        'date_display',
        'last_update',
        'timestamp',
        'updated'

    ]
def get_last_update(self,obj):
    return obj.updated.strftime('%b %d  %I:%M %p')

最佳答案

通过使用 SerializerMethodField,DRF 无法正确处理您的时区设置。

因此,要么将负担交给 DRF,然后使用源将 updated 映射到 last_update:

last_update = serializers.DateTimeField(source='updated', format='%b %d  %I:%M %p')
class Meta:
    model =  hashtag
    fields = [
        'id',
        'tag',     
        'date_display',
        'last_update',
        'timestamp',
        'updated'
    ]

或者自己处理时区:

def get_last_update(self,obj):
    tz = timezone.get_current_timezone()
    return obj.updated.astimezone(tz).strftime('%b %d  %I:%M %p')

关于python - 为什么 Django Rest 框架中的时间不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59050035/

相关文章:

django - Django ORM 中的 SQL 何时执行

python - Django 是否具有 Rails 的 "bundle install"的等价物?

python - 在 Django Rest Framework 中保存相关的嵌套对象

Django ORM 获取每行的最新版本(内连接)

django - 将 django 密码验证器与 django rest 框架 validate_password 集成

python - Robotframework导入自己的Python库

python - 将字符串转换为变量列表

python - 使用 AWS 部署 Django

python - Pandas df.idmax 在 0.22.0 版本中失败

python - 导入错误 : No module named openerp