Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change Datetime format django rest framework

I want to change date time format in django rest framework

I have implement one logic but it's not fullfill my requirement

Model

class User (models.Model):
    user_id = models.AutoField(primary_key=True)
    user_name = models.CharField(max_length=150)
    created_at = models.DateTimeField()

setting.py file I have define the datetime format

REST_FRAMEWORK = {

    'DATETIME_FORMAT': "%m/%d/%Y %H:%M:%S",
}

Query

data = User.objects.filter(pk=51)
serializer = UserSerializer(data, many=True)

result after serializer data

 {
      "user_id": 41406,
      "user_name": "[email protected]",
      "created_at": "09/26/2016 22:52:16",
 }

Now when I hit another model then datetime format is also same like this "09/26/2016 22:52:16" but i do not want this date format in anthor model.

Please let me know if we can change in particular Model datetime format and call it in serializer

like image 435
Sandeep Avatar asked Mar 31 '17 11:03

Sandeep


2 Answers

To provide more granular option, you can use SerializerMethodField:

class User (models.Model):
    user_id = models.AutoField(primary_key=True)
    user_name = models.CharField(max_length=150)
    created_at = models.SerializerMethodField()
    
    def get_created_at(self, obj):
        return obj.created_at.strftime("%Y-%m-%d %H:%M:%S")

And this format will only apply to this specific serializer attribute.

You can use this to any of your field with the format get_<field_name>. You can find more information in the documentation.

like image 147
PrynsTag Avatar answered Sep 19 '22 09:09

PrynsTag


You can override to_representation method in a model serializer which required different date output:

class UserSerializer(serializers.ModelSerializer):
    ...
    def to_representation(self, instance):
        representation = super(UserSerializer, self).to_representation(instance)
        representation['created_at'] = instance.created_at.strftime(<your format string>)
        return representation

Or you can write custom field and use it instead of default.

class UserSerializer(serializers.ModelSerializer):
    created_at = serializers.DateTimeField(format='%Y')
    # add read_only=True to the field in case if date created automatically
    ...
like image 44
Ivan Semochkin Avatar answered Sep 17 '22 09:09

Ivan Semochkin