首页 > 解决方案 > 为什么Django rest框架中的时间不正确

问题描述

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

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')

标签: pythondjangodjango-rest-frameworkdatetime-format

解决方案


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

因此,要么将负担交给 DRF,然后使用源映射updatedlast_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')

推荐阅读