django DRF -串行器保存数据但更改日期?

hc2pp10m  于 2023-03-04  发布在  Go
关注(0)|答案(1)|浏览(110)

print(serializer.data)的输出如下:

[OrderedDict([('last_price', '62.63'), ('name', None), ('country', None), 
('sector', None), ('industry', None), ('ticker', 'VUSA'), 
('high_price', 62.7075), ('last_date_time', '2023-03-01T00:00:00+04:00')])]

当我查看数据库(sql和postgres)时,last_date_time字段为:2023-02-28 20:00:00.
create语句:

def create(self, request, *args, **kwargs):
        if self.request.user.is_superuser:
            serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list))
            serializer.is_valid(raise_exception=True)
            print(serializer.data)
            self.perform_create(serializer)
            return Response({"Status": "We should be done"})

模型:

class UsStockPriceModel(models.Model):
    ticker = models.CharField(max_length=30, blank=False, db_index=True)
    name = models.CharField(max_length=150, blank=True, null=True)  # mainly for US stocks
    country = models.CharField(max_length=100, blank=True, null=True)
    sector = models.CharField(max_length=100, blank=True, null=True)
    industry = models.CharField(max_length=100, blank=True, null=True)
    last_price = models.FloatField(blank=True, null=True)
    high_price = models.FloatField(blank=True, null=True)
    last_date_time = models.DateTimeField(db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)

串行器:

class UsStockPriceSerializer(serializers.ModelSerializer):
    # ticker = models.CharField(max_length=30, blank=False)
    last_price = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    name = serializers.CharField(required=False, allow_null=True, allow_blank=True)  # mainly for US stocks
    country = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    sector = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    industry = serializers.CharField(required=False, allow_null=True, allow_blank=True)

    # last_date_time = models.DateTimeField()

    class Meta:
        model = UsStockPriceModel
        fields = '__all__'

    def validate_last_price(self, value):
        if not value:
            return None
        try:
            return float(value)
        except ValueError:
            raise serializers.ValidationError('Valid integer is required')

不知道这里出了什么问题。

gcuhipw9

gcuhipw91#

Postgres内部只存储UTC格式的日期,所以这就是你所看到的。你所显示的时间比你发布的时间早4个小时,而那个时间有+04:00作为偏移量。
https://www.postgresql.org/docs/14/datatype-datetime.html#DATATYPE-TIMEZONES
所有可识别时区的日期和时间都以UTC格式存储在内部。在显示给客户端之前,这些日期和时间将转换为TimeZone配置参数指定的时区中的本地时间。
2023-03-01T00:00:00+04:00 =〉2023-02-28T20:00:00+00:00

相关问题