2016-01-01 86 views
0

我想要做的是將unix_epoch轉換爲python dateTime,反之亦然,而序列化和desiarilization。我到目前爲止已經完成:在序列化和反序列化之前修改django rest框架字段

我的模型跟蹤:

class Track(models.Model): 
    uuid = models.UUIDField(null=True) 
    distance = models.FloatField(null=True) 
    dateCreated = models.DateTimeField(null=True) 
    dateClosed = models.DateTimeField(null=True) 


    def date_created_to_epoch(self): 
     return time.mktime(self.dateCreated.timetuple()) 

    def date_closed_to_epoch(self): 
     return time.mktime(self.dateClosed.timetuple()) 

我的模型點:

class Point(models.Model): 

    uuid = models.UUIDField(null=True) 
    track_uuid = models.UUIDField(null=True) 
    dateCreated = models.DateTimeField(null=True); 
    track = models.ForeignKey(Track, related_name='points') 

    def date_created_to_epoch(self): 
     return time.mktime(self.dateCreated.timetuple()) 

我的串行:

class PointSerializer(serializers.ModelSerializer): 
    dateCreated = serializers.ReadOnlyField(source='date_created_to_epoch') 

    class Meta: 
     model = Point 
     fields = ('uuid', 'lat', 'lng') 


class TrackSerializer(serializers.ModelSerializer): 
    points = PointSerializer(many=True) 
    dateCreated = serializers.ReadOnlyField(source='date_created_to_epoch') 
    dateClosed = serializers.ReadOnlyField(source='date_closed_to_epoch') 

    class Meta: 
     model = Track 
     fields = ('uuid', 'distance', 'dateCreated', 'dateClosed', 'comments', 'type', 'status', 'points') 

    def create(self, validated_data): 
     points_data = validated_data.pop('points') 
     track = Track.objects.create(**validated_data) 
     for point_data in points_data: 
      Point.objects.create(track=track, **point_data) 
     return track 

正如你看到的,我使用def date_created_to_epoch(self):method從數據庫到json轉換。我需要的是實現json(unix time)到數據庫(日期時間)轉換。我使用嵌套模型。我認爲我的方法不正確,有一種方法可以讓它變得更好。請幫忙。

回答

0

我會使用Django Rest Framework的built in DateTime fields而不是原始.ReadOnlyField。您可以通過將read_only=True傳遞給該字段的構造函數來只讀任何字段。

相關問題