Home > database >  How edit the value of post inside serializer in Django?
How edit the value of post inside serializer in Django?

Time:03-28

I am using Django and Django Rest Framework. Below the Register serializer is given and the user's birthday in datetime format. However the birthdate sent inside post is in timestamp format. I want to convert timestamp that posted from user's device to datetime inside serializer. How to do it?

class Register_Serializer(serializers.ModelSerializer):
      
        password2 = serializers.CharField(style={"input_type": "password"}, write_only=True)
        class Meta:
            model = Tuser
            fields = [Constants.EMAIL, Constants.PASSWORD, Constants.PASSWORD2, Constants.BIRTH_DATE]
            extra_kwargs = {
                "password": {"write_only": True}
            }
        
        

CodePudding user response:

please try this,

class CustomField(serializers.DateTimeField):
    def to_internal_value(self, data):
        return datetime.datetime.fromtimestamp(data )

class Register_Serializer(serializers.ModelSerializer):
    birthday = CustomField() 
    
    password2 = serializers.CharField(style={"input_type": "password"}, write_only=True)
    class Meta:
        model = Tuser
        fields = [Constants.EMAIL, Constants.PASSWORD, Constants.PASSWORD2, Constants.BIRTH_DATE]
        extra_kwargs = {
            "password": {"write_only": True}
        }
    
  • Related