如何在Django Rest框架中保存时间戳字段

时间:2018-06-20 10:25:46

标签: django django-rest-framework

serializer.py文件

class TabsionSerializer(serializers.ModelSerializer):
     class Meta:
        model = Tabsion
        fields = ('sen_id','det_id','latitude','longitude','start_or_end','user_id','username','type','timestamp')


在上面,时间戳字段由数据库自动设置,类型字段默认设置为1。因此这些字段没有添加到数据库中。

View.py

class StartReportSave(viewsets.ModelViewSet):
    def post(self,request,format=None):
        reqData  = json.loads(request.body.decode("utf-8"))
        savData  = {}
        savData['sen_d'] = reqData['data']['section']['id'];
        savData['det_id'] = reqData['data']['depot']['id'];
        savData['latitude'] = reqData['data']['locationData']['latitude'];
        savData['longitude'] = reqData['data']['locationData']['longitude'];
        savData['start_or_end'] = reqData['data']['start_or_end'] ;
        savData['username']= reqData['userData'][0]['username'];
        savData['user_id']= reqData['userData'][0]['id'];   
        serializer = TabsionSerializer(data=savData)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data,status=201))

        return JsonResponse(savData,safe=False)


model.py

class Tabsion(models.Model):
    sen_id = models.IntegerField()
    det_id = models.IntegerField()
    timestamp = models.DateTimeField()
    latitude = models.CharField(max_length=100)
    longitude = models.CharField(max_length=100)
    start_or_end = models.IntegerField()
    user_id = models.IntegerField()
    username = models.CharField(max_length=1000)
    type = models.IntegerField()

    class Meta:
        managed = False
        db_table = 'tab_reporting_session'

当我尝试添加数据时出现错误

  

时间戳记,类型字段为必填

我该如何解决?

获取此插入记录的ID并将其添加到另一个日志表的正确方法是什么?

3 个答案:

答案 0 :(得分:1)

  1. 使用只读字段

    class TabsionSerializer(serializers.ModelSerializer):
        class Meta:
            model = Tabsion
            fields = ('sen_id','det_id','latitude','longitude','start_or_end','user_id','username','type','timestamp')
            read_only_fields = ('type','timestamp') 
    
  2. save_data由所需的ID组成。

    save_data = serializer.save(data=data)
    
    instance_id = save_data.id`
    

答案 1 :(得分:1)

class TabsionSerializer(serializers.ModelSerializer):
 class Meta:
    model = Tabsion
    fields = ('sen_id','det_id','latitude','longitude','start_or_end','user_id','username','type','timestamp')
    extra_kwargs = {'type': {'read_only': True, 'required': False}, 'timestamp': {'read_only': True, 'required': False}}
  

在extra_kwargs中设置read_only = True将为您解决问题。

了解更多:http://www.django-rest-framework.org/api-guide/serializers/#additional-keyword-arguments

  

或者您可以使用read_only_fields

class TabsionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tabsion
        fields = ('sen_id','det_id','latitude','longitude','start_or_end','user_id','username','type','timestamp')
        read_only_fields = ('type','timestamp')

了解更多:http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields

  

推荐第二种解决方案。

答案 2 :(得分:0)

您可以在Tabsion模型中为时间戳字段立即设置自动

timestamp = models.DateTimeField(auto_now=True)