如何将多个{json.api}格式的对象发布到Django模型?

时间:2019-07-19 09:26:44

标签: django-models django-rest-framework django-views bulkinsert

这是我的代码段,

模型OptionalFieldsByOrganization.py

from django.db import models

from model_utils import Choices

from proposal.models import Organization
from proposal.models.proposal_configurable_fields import ProposalConfigurableFields


class OptionalFieldsByOrganization(models.Model):
    STATUS = Choices(
        (0, 'hidden', 'Hidden'),
        (1, 'optional', 'Optional'),
        (2, 'required', 'Required'))

    organization = models.ForeignKey(Organization, on_delete=models.PROTECT)
    configurable_fields = models.ForeignKey(ProposalConfigurableFields, on_delete=models.PROTECT)
    status = models.IntegerField(choices=STATUS, default=STATUS.hidden)

    class Meta:
        permissions = (
            ('view_optionalfieldsbyorganization', 'Can view Optional Fields By Organization'),)

序列化器

from rest_framework_json_api import serializers
from proposal.models import (
organization, proposal_configurable_fields)
from rest_framework_json_api.relations import ResourceRelatedField

from proposal.models import OptionalFieldsByOrganization


class OptionalFieldsByOrganizationSerializer(serializers.ModelSerializer):

    class Meta:
        model = OptionalFieldsByOrganization
        #fields = ['status']
        fields = "__all__"

ViewSet

from sis_common.views import BaseViewSet
from proposal.models import organization

from proposal.serializers.optional_fields_by_organization import (
    OptionalFieldsByOrganizationSerializer)
from proposal.models.optional_fields_by_organization import (
    OptionalFieldsByOrganization)


class OptionalFieldsByOrganizationViewSet(BaseViewSet):
    queryset = OptionalFieldsByOrganization.objects.all().order_by('pk')
    serializer_class = OptionalFieldsByOrganizationSerializer

有了这个配置,我就能在一个数组中获取多个记录。像这样

curl -X GET \
  http://localhost:8000/v1/optionalfieldsbyorganizations \
  -H 'Accept: */*' \
  -H 'Authorization: Basic YWRtaW46YWRtaW4xMjM=' \
  -H 'Content-Type: application/vnd.api+json' \
{
    "links": {
        "first": "http://localhost:8000/v1/optionalfieldsbyorganizations?page%5Bnumber%5D=1",
        "last": "http://localhost:8000/v1/optionalfieldsbyorganizations?page%5Bnumber%5D=1",
        "next": null,
        "prev": null
    },
    "data": [
        {
            "type": "OptionalFieldsByOrganization",
            "id": "1",
            "attributes": {
                "status": 0
            },
            "relationships": {
                "organization": {
                    "data": {
                        "type": "Organization",
                        "id": "1"
                    }
                },
                "configurable_fields": {
                    "data": {
                        "type": "ProposalConfigurableFields",
                        "id": "1"
                    }
                }
            }
        },
        {
            "type": "OptionalFieldsByOrganization",
            "id": "2",
            "attributes": {
                "status": 1
            },
            "relationships": {
                "organization": {
                    "data": {
                        "type": "Organization",
                        "id": "1"
                    }
                },
                "configurable_fields": {
                    "data": {
                        "type": "ProposalConfigurableFields",
                        "id": "2"
                    }
                }
            }
        },
        {
            "type": "OptionalFieldsByOrganization",
            "id": "3",
            "attributes": {
                "status": 0
            },
            "relationships": {
                "organization": {
                    "data": {
                        "type": "Organization",
                        "id": "1"
                    }
                },
                "configurable_fields": {
                    "data": {
                        "type": "ProposalConfigurableFields",
                        "id": "1"
                    }
                }
            }
        }
    ],
    "meta": {
        "pagination": {
            "page": 1,
            "pages": 1,
            "count": 3
        }
    }
}

现在,我想批量发布和修补同一资源。有效载荷看起来像这样,

{
    "data": [
        {
            "type": "OptionalFieldsByOrganization",
            "attributes": {
                "status": 2
            },
            "relationships": {
                "organization": {
                    "data": {
                        "type": "Organization",
                        "id": "2"
                    }
                },
                "configurable_fields": {
                    "data": {
                        "type": "ProposalConfigurableFields",
                        "id": "2"
                    }
                }
            }
        },{
            "type": "OptionalFieldsByOrganization",
            "attributes": {
                "status": 1
            },
            "relationships": {
                "organization": {
                    "data": {
                        "type": "Organization",
                        "id": "2"
                    }
                },
                "configurable_fields": {
                    "data": {
                        "type": "ProposalConfigurableFields",
                        "id": "3"
                    }
                }
            }
        }]
}

要实现此目标,我应该对代码进行哪些更改? 我在{json.api}中了解了extensions,但是不确定如何使用它?

1 个答案:

答案 0 :(得分:0)

我相信一种可能的方法如下。如果您坚持要在请求的“数据”字段中发送对象。

创建一个特殊的视图来处理批量,请在post方法中创建一个操作:

class BulkView(generics.GenericAPIView):

   serializer_class = OptionalFieldsByOrganizationSerializer
   queryset = OptionalFieldsByOrganization.objects.all()

   def post(self, request, *args, **kwargs):
       ser = self.get_serializer(data=request.data["data"], many=True)

       ser.is_valid(raise_exception=True)

       ser.save()

       return Response(ser.data)