我是django rest框架的新手,并创建了一个示例Employee
模型。
我的 models.py :
class Employees(models.Model):
created = models.DateTimeField(auto_now_add=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
我的 serializers.py :
class EmployeeSerializer(serializers.Serializer):
class Meta:
model = Employees
fields = ('first_name','last_name')
这样可行但我想要一个额外的字段full_name
,它将是first_name + last_name
。
如何在full_name
?
serializers.py
答案 0 :(得分:65)
我在这里看到两种方式(我更喜欢第一种方式,因为你可以在应用程序的其他部分重复使用它):
将计算属性添加到模型中并将其添加到序列化程序 使用a readonly field with source=
# models.py
class Employees(models.Model):
created = models.DateTimeField(auto_now_add=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
@property
def full_name(self):
return self.first_name + self.last_name
#serializes.py
class EmployeeSerializer(serializers.ModelSerializer):
full_name = serializers.Field(source='full_name')
class Meta:
model = Employees
fields = ('first_name','last_name', 'full_name')
使用SerializerMethodField (你的模型不变)
class EmployeeSerializer(serializers.ModelSerializer):
full_name = serializers.SerializerMethodField('get_full_name')
def get_full_name(self, obj):
return obj.first_name + obj.last_name
class Meta:
model = Employees
fields = ('first_name','last_name', 'full_name')
答案 1 :(得分:4)
如果Employee
是登录用户,那么我们大多数人都会使用django.auth.User
,我将分享Employee
如何作为另一个Profile
实施的扩展django用户)。还添加了full_name.read_only
,first_name.write_only
和last_name.write_only
# models.py
class Employee(models.Model):
"""User Profile Model"""
user = models.OneToOneField('auth.User')
# serializers.py
class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
username = serializers.CharField(source='user.username')
email = serializers.EmailField(source='user.email')
first_name = serializers.CharField(
source='user.first_name', write_only=True)
last_name = serializers.CharField(
source='user.last_name', write_only=True)
name = serializers.CharField(
source='user.get_full_name', read_only=True)
class Meta:
model = Employee
fields = (
'url', 'username', 'email',
'first_name', 'last_name', 'name')
depth = 1
答案 2 :(得分:3)
SerializerMethodField工作正常,我们也可以将数据存储在序列化程序对象中,让方法get_field_name
使用它。
示例:
class MySerializer(serializers.ModelSerializer):
statistic = serializers.SerializerMethodField()
def __init__(self, instance=None, data=serializers.empty, statistic=None, **kwargs):
super(MySerializer, self).__init__(instance=instance, data=data, **kwargs)
self.statistic = statistic
def get_statistic(self, obj):
if self.statistic is None:
return serializers.empty
return self.statistic.get(obj.id, {})