Search code examples
djangotimestamptastypietype-conversion

Processing data before saving to database Django Tastypie


I send a string to the server and I want to convert it to a Timestamp before saving in the database.

I want to do this function before saving the data.

date = time.strptime(date, "%Y-%m-%d %H:%M:%S")

date is sent as a string and I want to convert it to a TIMESTAMP before saving in database.

Thank you for your help.

#models.py
from tastypie.utils.timezone import now
from django.db import models
from django.utils.text import slugify


class Entry(models.Model):
    pub_date = models.DateTimeField()
    Temperature = models.FloatField()

    def __unicode__(self):
        return self.title

#api.py
from tastypie import fields
from tastypie.resources import ModelResource
from models import Entry
from tastypie.authorization import Authorization 

class EntryResource(ModelResource):
    class Meta:
        queryset = Entry.objects.all()
        resource_name = 'entry'
        authorization = Authorization() 

Solution

  • Use the hydrate method on your resource.

    class EntryResource(ModelResource):
    
    
        def hydrate(self, bundle):
    
            if  field in bundle.data:
                        date = bundle.data['pub_date']
                        bundle.data['pub_date'] =  time.strptime(date, "%Y-%m-%d %H:%M:%S")
    
            return bundle