Akhil Sahu
Akhil Sahu

Reputation: 637

How to save timestamp field in django rest framework

The serializer.py file

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


In the above the timestamp field is automatically set by database and type field is set by default to one. So these fields were not added to the database.

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'

When I try to add data the error shows up

Timestamp , Type field are required

How can I resolve this?

What will be the correct way to fetch the id of this inserted record and also add it to another log table?

Upvotes: 1

Views: 3033

Answers (3)

Ali
Ali

Reputation: 2591

You can set auto now for timestamp field in Tabsion model

timestamp = models.DateTimeField(auto_now=True)

Upvotes: 1

Akhil Sahu
Akhil Sahu

Reputation: 637

  1. Use read only field

    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. The save_data consist of the id required.

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

Upvotes: 0

Tevin Joseph K O
Tevin Joseph K O

Reputation: 2654

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}}

Setting read_only=True in extra_kwargs will do the trick for you.

Read more: http://www.django-rest-framework.org/api-guide/serializers/#additional-keyword-arguments

Or you can use 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')

Read more: http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields

The second solution is recommended.

Upvotes: 1

Related Questions