使用DateTime字段保存Django模型

时间:2016-08-21 11:28:21

标签: python django datetime django-rest-framework

型号:

class Meal(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    collection_from = models.DateTimeField(blank=False, null=False)
    discount_price = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=4)
    normal_price = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=4)
    available_count = models.IntegerField(blank=False, null=False)
    name = models.CharField(blank=False, null=False, max_length=255)
    active = models.BooleanField(blank=False, null=False, default=True)

现在,当我保存它的实例时,created_atupdated_at值设置正确,例如:2016-08-21 13:13:57.585472+02collection_from值应该与之前的两个值几乎相同,但是它会被设置为指向第二天,例如:2016-08-22 01:00:00+02我完全没有得到:)。 collection_from值看起来与浏览器发送时的值相同:2016-08-21 23:00。我相信我在settings.py文件中设置了适当的设置:

TIME_ZONE = 'UTC'

USE_TZ = True

那么这里的问题是什么?如何使Django保存collection_from的值与created_atupdated_at相同?

修改

我注意到当检索到这个模型的值时,我得到了正确的值 - 所以如果我collection_from字段的值等于数据库中的2016-08-22 01:00:00+02,那么输出就是转换为初始值,2016-08-21 23:00。那么现在问题会发生变化 - 为什么created_atupdated_at字段与此字段之间存在差异?

EDIT2:

我认为没有必要(正如我所描述的那样,我提供了collection_from值),但这里是POST请求正文:

[{"collection_from":"2016-08-21 23:00","discount_price"
:"10","normal_price":"20","available_count":"4","name":"pizza"}]

DRF视图保存它:

class MealsCrudView(CreateAPIView):
    serializer_class = MealSerializer

序列化器:

class MealSerializer(serializers.ModelSerializer):   
    class Meta:
        model = Meal

1 个答案:

答案 0 :(得分:1)

你有没有尝试过:

time.sleep(1)

而不是发送当前时间?

相关问题