有没有办法从模型两个字段创建序列化器而不是模型可写字段?这是我的序列化器
using System.Globalization;
// ...
yourDate.ToString(new CultureInfo("es-ES")); // Convert the date to a normal date string with Spain's Spanish culture
我想将firts_name和last_name连接到全名
答案 0 :(得分:2)
您可以将serializers.CharField()
与write_only
属性一起使用;
class UserProfileSerializer(serializers.ModelSerializer):
full_name = serializers.CharField(max_length=225, write_only=True,
required=False, allow_null=True)
class Meta:
model = users.models.User
fields = (
'phone_number',
'email',
'city',
'full_name'
)
然后您将能够发送json数据;
{
"phone_number": "123456789",
"email": "foo@bar.com",
"city": "Foo",
"full_name": "My Full Name"
}
并用于通过serializer.is_valid()
方法获得该值;
full_name = serializer.validated_data.get('full_name', '')
# full_name --> My Full Name
答案 1 :(得分:1)
您可以使用SerializerMethodField
从名字 + 姓氏构建全名:
from rest_framework import serializers
class UserProfileSerializer(serializers.ModelSerializer):
full_name = serializers.SerializerMethodField()
class Meta:
model = users.models.User
fields = (
'phone_number',
'email',
'city',
'full_name'
)
def get_full_name(self, instance):
return "{} {}".format(instance.first_name, instance.last_name)