【问题标题】:JSON [{"non_field_errors": ["Invalid data"]}]} Django Rest FrameworkJSON [{"non_field_errors": ["Invalid data"]}]} Django Rest 框架
【发布时间】:2015-04-05 05:14:42
【问题描述】:

我有一些序列化程序,其中有一些元素,并希望它在我为 InvoiceDictionarySerializer 创建 POST 方法时发布它。不知道如何使它正常工作。有什么建议吗?

我的代码如下:

class InvoiceDictionaryElementSerializer(serializers.ModelSerializer):
class Meta:
    model = InvoiceDictionaryElement
    fields = (
        'name', 'unit', 'quantity', 'value'
    )


class InvoiceDictionarySerializer(serializers.ModelSerializer):
    invoice_elements = InvoiceDictionaryElementSerializer()
    class Meta:
        model = InvoiceDictionary
        fields = (
            'name', 'is_active', 'invoice_elements')

以及我对 JSON 的请求:

{
"name": "invoice", 
"is_active": true, 
"invoice_elements":  [{
        "name": "name", 
        "unit": "12", 
        "quantity": "15.00", 
        "value": "7.00"
    }]

}

出现错误:

{"invoice_elements": [{"non_field_errors": ["Invalid data"]}]}

在我的控制台输出中,我有 400 错误(错误请求)。不知道 JSON 的语法不好还是什么?

【问题讨论】:

  • 你的请求怎么样?你能发布代码/命令吗?
  • 我使用邮递员并且代码已经粘贴了

标签: json django django-rest-framework serialization


【解决方案1】:

由于invoice_elements是元素列表,所以需要指定many=True

class InvoiceDictionarySerializer(serializers.ModelSerializer):
    invoice_elements = InvoiceDictionaryElementSerializer(many=True)
    class Meta:
        model = InvoiceDictionary
        fields = (
            'name', 'is_active', 'invoice_elements')

    def create(self, validated_data):
        ...

    def update(self, instance, validated_data):
        ...

You should also implement .create().update() 处理保存多个对象的序列化程序的方法。

【讨论】:

    【解决方案2】:
    example_entry = serializers.CharField(required=True/False)
    

    问题出现在序列化器字段中。用正确的标志配置它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 2017-03-19
      • 2014-02-17
      • 2017-08-21
      • 2018-09-16
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多