Reputation: 321
why when I updated entry in the database the updated time field in the model
updated = models.DateTimeField(auto_now=True)
is updated correctly according to timezone in my settings file but when it appeared in the Django rest Framework terminal it is shifting back 3 hours
The following code is for the Model:
class hashtag(models.Model):
tag = models.CharField(max_length=120)
count = models.IntegerField(default=0,blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
the following code is for DRF:
last_update = serializers.SerializerMethodField()
class Meta:
model = hashtag
fields = [
'id',
'tag',
'date_display',
'last_update',
'timestamp',
'updated'
]
def get_last_update(self,obj):
return obj.updated.strftime('%b %d %I:%M %p')
Upvotes: 1
Views: 296
Reputation: 20966
By using SerializerMethodField
you are out of the reach for DRF to properly handle your timezone settings.
So either stick the burden to DRF and use a source to map updated
to last_update
:
last_update = serializers.DateTimeField(source='updated', format='%b %d %I:%M %p')
class Meta:
model = hashtag
fields = [
'id',
'tag',
'date_display',
'last_update',
'timestamp',
'updated'
]
Or handle the timezone yourself:
def get_last_update(self,obj):
tz = timezone.get_current_timezone()
return obj.updated.astimezone(tz).strftime('%b %d %I:%M %p')
Upvotes: 1