python - Django Rest Framework - 将多对多字段属性序列化为 POST 操作

标签 python django serialization django-rest-framework

我有以下模型

class Metrics(models.Model):
    name = models.CharField(
        max_length=255,
        blank=True,
        verbose_name='Nombre'
    )
    value = models.DecimalField(
        max_digits = 5,
        decimal_places = 3,
        verbose_name = 'Valor',
        null = True,
        blank = True
    )

在另一个模型中,我与 Metrics 模型有 ManyToManyField 关系

class PatientMonitoring(models.Model):
    metrics = models.ManyToManyField(Metrics, verbose_name='Métricas', 

)

我的serializers.py文件看起来是这样的:

class MetricsSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model= Metrics
        fields = ('name','value',)

class PatientMonitoringSerializer(serializers.HyperlinkedModelSerializer):
    metrics = MetricsSerializer(many=True)

    class Meta:
        model = PatientMonitoring
        fields = ('url', 'id', 'metrics')
        #depth=2

    def create(self,validated_data):
        metrics_data = validated_data.pop('metrics')
        metric = Metrics.object.create(**validated_data)
        for metric_data in metrics_data:
            Metrics.objects.create(metric=metric,**metrics_data)
        metric.save()
        return metric

结果是我的模型正在被序列化,但它们没有“具有 POST 权限,并且表单 View 没有被更新或创建”

enter image description here

我正在定义创建方法,which is described这里用于处理模型序列化和写入/发布操作,但我不明白该过程是如何执行所有这些功能的。 在这种情况下,如何使用 POST 方法处理我的模型和属性?

*更新

我已经通过 curl 执行了 POST 操作,例如 @RossRogers 和 @Nirri 建议我,行为如下:

curl -X POST http://localhost:8000/api/patientmonitoring/ -d "metrics=Grados" 

我收到与我的 create 方法相关的消息

File "/home/bgarcial/.virtualenvs/nrhb_dev/lib/python3.5/site-packages/rest_framework/serializers.py", line 191, in save
    self.instance = self.create(validated_data)
  File "/home/bgarcial/workspace/neurorehabilitation-project/patient_monitoring/serializers.py", line 37, in create
    metric = Metrics.object.create(**validated_data)
AttributeError: type object 'Metrics' has no attribute 'object'
[28/Jun/2016 17:19:16] "POST /api/patientmonitoring/ HTTP/1.1" 500 104669

最佳答案

嗯,正如它所说,HTML 输入不支持列表。

正如您在此处看到的 ( http://www.django-rest-framework.org/topics/3.2-announcement/ ),计划在 3.3 版本中发布,但发行说明中没有提及。

这并不意味着您没有执行 POST 请求的权限。尝试使用原始 JSON(如帖子评论中所建议的那样)使用 DHC、Postman 甚至curl 发出 POST 请求。

关于python - Django Rest Framework - 将多对多字段属性序列化为 POST 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38057155/

相关文章:

python - 如何从另一个模块扩展模板?

下课后出现 "$1"的 java.io.NotSerializableException

python - 遍历目录并检查文件的大小

java - 开源 ETL 框架

django - 命名 URL 模式抛出 NoReverseMatch 异常

python - 在 Django >= 1.5 中引用用户模型的最佳方式

Angular 2(或 4)对象序列化

serialization - 在磁盘上存储一组 protobuf

python - 编译器找不到 Py_InitModule() .. 它是否已被弃用,如果是,我应该使用什么?

python - printf 样式格式字符串的解析器