我想创建一个表单字段,在模型中的特定字段中添加一些输入字段和值。我是这个python的新手,Django休息了。注意:我不应该更改模型和序列化程序。我可以为此创建新的序列化器。
我坚持这个
我的期望:
{
"id" : "6fe7c9dd-8d69-4337-8f96-6d67463f6a1d",
"name": "xyz",
"age" : 22,
"additional_detail":{
"details": {
"bloodgroup" : "A+ve",
"city" : "abc"
}
}
}
models.py
class Student(models.model)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField()
age = models.IntergerField()
additional_detail = JSONField(_details)
serizlizer.py
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'
views.py
class StudentViewSet(viewsets.ModelViewSet):
queryset = student.objects.all()
serializer_class = StudentSerializer
我想像这样插入“additional_detail”字段
"details": {
"bloodgroup" : "A+ve",
"city" : "abc"
}
我想通过id将这些字段作为put或patch方法插入到新视图中。 是否可以通过对那些添加文件进行非模型序列化? 请将所有.py文件的完整解决方案发送给我
答案 0 :(得分:0)
快速解决方案可以实现to_representation方法。
class StudentSerializer(serializers.ModelSerializer):
def to_representation(self, student):
# Serialize the student object
serialized_data = super(StudentSerializer, self).to_representation(student)
# Include your non-model data
serialized_data["additional_details"]["details"] = {
"bloodgroup" : "A+ve",
"city" : "abc"
}
return serialized_data
class Meta:
model = Student
fields = '__all__'
希望它有所帮助!