Django序列化模型和非模型serilizer的视图

时间:2017-05-21 06:09:37

标签: django python-2.7 django-models django-views django-rest-framework

期望:

Expected output:
 { 

     "id": 123,
     "name": "abc",
     "body_measurement": 
           {
             "weight": 75,
             "bp": "normal,
             "bloodgroup": "A-positive",
           },
   }

models.py

class Health(models.Model):
     name = models.CharField(max_length=64, unique=True)
     body_measurment = JSONField(_('measurments'),dump_kwargs={'indent': 4})

serializer.py

   class HealthSerializer(serializers.ModelSerializer):

        class Meta:
            model = Health
            fields = '__all__'

   class MeasurementSerializer(serializer,Serializer):

        weight = serializer.IntegerField()
        bp = serializer.CharField()
        bloodgroup = serializer.CharField()

views.py

   class HealthViewSet(viewsets.ModelViewSet):
        queryset = Health.objects.all()
        serializer_class = HealthSerializer

如何在不添加模型的情况下将一组键值添加到body_measurment中。

1 个答案:

答案 0 :(得分:0)

在您的模型上使用JsonField body_measurment字段:

class HealthSerializer(serializers.ModelSerializer):
    body_measurement = serializers.JsonField()

        class Meta:
            model = Health
            fields = '__all__'

使用此功能可以在body_measurement字段中保存任何有效的json

在这里阅读json字段:http://www.django-rest-framework.org/api-guide/fields/#jsonfield