如何在 Django 的序列化程序中编辑 post 的值?
How edit the value of post inside serializer in Django?
我正在使用 Django 和 Django Rest Framework。 Register
序列化程序下方给出了 user
的生日 datetime
格式。但是 post 中发送的生日是 timestamp
格式。
我想将 post 从用户设备编辑的 timestamp
转换为序列化程序中的 datetime
。怎么做?
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}
}
请试试这个,
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}
}
我正在使用 Django 和 Django Rest Framework。 Register
序列化程序下方给出了 user
的生日 datetime
格式。但是 post 中发送的生日是 timestamp
格式。
我想将 post 从用户设备编辑的 timestamp
转换为序列化程序中的 datetime
。怎么做?
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}
}
请试试这个,
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}
}