在Django-Rest-framework POST调用中获取模型的多个值

时间:2017-03-05 08:58:35

标签: django django-rest-framework

我正在使用Django Rest Framework收集一些数据。我想创建一个API来接受POST调用和所需的query_set,它将是Address。现在我希望API应该接受多个Address,因此POST请求将包含类似于 -

的数据集
{
   {
      "some_id": id1,
      "address_line_1": some random address 1
      "address_line_2": some random address 2
   },
   {
      "some_id": id2,
      "address_line_1": some random address 1
      "address_line_2": some random address 2
   }
} 

我的地址模型如下:

class Address(models.Model):
   some_id = models.IntegerField()
   address_line_1 = models.CharField(max_length = 200)
   address_line_2 = models.CharField(max_length = 200)

我的序列化器为 -

class AddressSerializer(serializers.ModelSerializer):
    class Meta:
       model = Address
       fields = ('some_id', 'address_line_1', 'address_line_2',)

我不确定使用哪个视图来实现此功能。此外,我想渲染一个表单,类似于 GenericAPIView 提供的表单,包含从浏览器点击API时地址模型的所有字段。像 -

这样的东西

Api for a random model with fields: "first", "second"

我是Django Rest Framework的新手,所以非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

首先,以下不是有效的JSON。

{
   {
      "some_id": id1,
      "address_line_1": some random address 1
      "address_line_2": some random address 2
   },
   {
      "some_id": id2,
      "address_line_1": some random address 1
      "address_line_2": some random address 2
   }
} 

它必须有一个与之关联的密钥。所以它应该像

{
   addresses: [
      {
         "some_id": id1,
         "address_line_1": some random address 1
         "address_line_2": some random address 2
      },
      {
         "some_id": id2,
         "address_line_1": some random address 1
         "address_line_2": some random address 2
      }
   ]
}

要接受上述内容,您必须创建另一个序列化程序,如

class AddressListSerializer(serializers.Serializer):
    addresses = AddressSerializer(many=True)

然后在您的视图中使用上面的序列化程序。