自定义模型字段以进行序列化
customising a model field for serialization
我正在做一个关于 django 的项目。我有一个 EmployeeProfile 模型,其中包含多个字段以及包含以下数据的现场教育 -(学院、年份、课程、描述)。
在模型中,我以分隔字段的形式存储数据。
例如教育的样本值 - “ XYZ 学院 | 1994 | Btech | blabla “
但我想将它与字典形式的其他字段一起序列化,即
{ education:{ year: '1994', course: ' Btech', college: ' XYZ ', description: 'blabla'}}
将来我也想将它用作由“;”分隔的数组
但现在不一定需要。
我是 django restframework 的新手...
首先可以使用split拆分education字段值。
然后你可以相应地序列化它。
class CustomModel:
def __init__(self, year,course,college,description):
self.year = year
self.course = course
self.description = description
self.college = college
class CustomSerializer(NonNullSerializer):
year = serializers.IntegerField()
course = serializers.CharField()
description = serializers.CharField()
college = serializers.CharField()
将此添加到 view.py
education_value = ...
year,course,college,description = education_value.split('|')
education_obj = CustomModel(year=year,course=course,college=college,description=description)
serialized_data = CustomSerializer(education_obj)
return serialized_data.data
希望对您有所帮助
我正在做一个关于 django 的项目。我有一个 EmployeeProfile 模型,其中包含多个字段以及包含以下数据的现场教育 -(学院、年份、课程、描述)。 在模型中,我以分隔字段的形式存储数据。 例如教育的样本值 - “ XYZ 学院 | 1994 | Btech | blabla “
但我想将它与字典形式的其他字段一起序列化,即
{ education:{ year: '1994', course: ' Btech', college: ' XYZ ', description: 'blabla'}}
将来我也想将它用作由“;”分隔的数组 但现在不一定需要。
我是 django restframework 的新手...
首先可以使用split拆分education字段值。 然后你可以相应地序列化它。
class CustomModel:
def __init__(self, year,course,college,description):
self.year = year
self.course = course
self.description = description
self.college = college
class CustomSerializer(NonNullSerializer):
year = serializers.IntegerField()
course = serializers.CharField()
description = serializers.CharField()
college = serializers.CharField()
将此添加到 view.py
education_value = ...
year,course,college,description = education_value.split('|')
education_obj = CustomModel(year=year,course=course,college=college,description=description)
serialized_data = CustomSerializer(education_obj)
return serialized_data.data
希望对您有所帮助