Skip to main content
 首页 » 编程设计

python之使用 DateTime 字段保存 Django 模型

2025年04月02日24jackei

型号:

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_at 和 updated_at 值已正确设置,例如:2016-08-21 13:13:57.585472 +02。 collection_from 值应该与前两个值几乎相同,但它被设置为指向第二天,例如:2016-08-22 01:00:00+02 我根本不明白 :)。 collection_from 值在浏览器发送时看起来像这样:2016-08-21 23:00。我相信我在 settings.py 文件中设置了正确的设置:

TIME_ZONE = 'UTC' 
 
USE_TZ = True 

那么这里有什么问题呢?如何使 Django 以与 created_at 或 updated_at 相同的方式保存 collection_from 值?

编辑:

我注意到,当检索到该模型的值时,我得到了正确的值 - 所以如果我 collection_from 字段的值等于 2016-08-22 01:00 :00+02 在数据库中,在输出中它被转换为初始值,所以 2016-08-21 23:00。所以现在问题变了 - 为什么 created_at 和 updated_at 字段与这个字段有区别?

编辑2:

我不认为这是必要的(因为我已经很好地描述了我如何提供 collection_from 值),但这是 POST 请求正文:

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

DRF View 保存它:

class MealsCrudView(CreateAPIView): 
    serializer_class = MealSerializer 

和序列化器:

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

请您参考如下方法:

你试过吗:

from django.utils import timezone 
 
class Meal(models.Model): 
    ... 
    collection_from = models.DateTimeField(default=timezone.now) 
    ... 

而不是发送当前时间?