DRF序列化器通过REST API与第三方应用一起操作

问题描述 投票:0回答:1

由于一张图片值得一千个字,所以我们就这样做。因此,我正在尝试通过REST CRUD API使用第三方应用程序。

现在,我想使用Django Rest API路由器以及它将带给我的应用程序的所有好处。要使用路由器,我将不得不使用ViewSet。我不需要使用任何模型来代替模型,因为我不必存储任何数据(也许根本不需要此数据?)。

问题是,如何创建序列化器来转换来自第三方服务的复杂json数据,将其转换并将其发送到Fronted。但是,当我更改前端应用程序上的数据以传播更改并更新第三方应用程序时。

enter image description here

到目前为止,我有这个:

urls.py

router.register(r'applications', ApplicationViewSet, base_name='application')

models.py

class Application(object):

    def __init__(self, name, color):
        self.name = name
        self.color = color

serializers.py

class ApplicationSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=256)
    #color = ??? How to transform and serialize dict value to field ?

views.py

class ApplicationViewSet(ViewSet):

    def create(self, request):
        # I guess that this logic should be handled by serializes as well?. 
        name = request.data.get('name')
        color = request.data.get('color')
        result = third_party_service.create_application(request, name)
        app = Application(**result)
        if color:
            app.color = color
            third_party_service.update_application(request, app)
        return Response(app)

    def list(self, request):
        queryset = third_party_service.get_applications(request)
        serializer = ApplicationSerializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        app = third_party_service.get_application(request, pk)
        serializer = ApplicationSerializer(instance=app)
        return Response(serializer.data)

JSON来自第三方应用程序:

{
  "name": "Application",
  "attributeCollection": {
    "attributeArray": [
      {
        "name": "color",
        "value": [
          "red",
          "green"
        ]
      },
      {
        "name": "text",
        "value": [
          "bold"
        ]
      }
    ]
  }
}

发送到前端的JSON:

{
  "name": "Application",
  "color": ["red", "green"]
}

我不是DRF的高级用户,所以也许我以错误的方式使用它。关于如何实现这一目标的任何建议将非常有帮助!

python django django-rest-framework serializer
1个回答
0
投票

您可以使用serializer-method-field从字典中获取价值。

下面是根据您提供的样本获得颜色的代码。

class ApplicationSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=256)
    color = = serializers.SerializerMethodField()

    get_color(self, obj):
        attribute_array = obj['attributeCollection']['attributeArray']
        color_attr = [attr for attr in attribute_array if attr['name'] == 'color']
        if color_attr:
            return color_attr[0]['value']

        return []

您还可以使用generator-expression从数组中找到color_attribute。

color_attr = next((attr for attr in attribute_array if attr["name"] == "color"), None)
return color_attr['value] if color_attr else []
© www.soinside.com 2019 - 2024. All rights reserved.