一图胜千言,就这样吧。因此,我尝试通过 REST CRUD API 操作第三方应用程序。
现在,我想使用 Django Rest API 路由器以及它将给我的应用程序带来的所有好处。要使用路由器,我必须使用 ViewSets。我只使用简单的 python 类而不是模型,因为我不必存储任何数据(也许根本不需要?)。
问题是,如何创建序列化器来转换来自第三方服务的复杂 json 数据,转换它并将其发送到 Fronted。但是,当我更改前端应用程序上的数据以传播更改并更新第三方应用程序时。
到目前为止我有这个:
url.py
router.register(r'applications', ApplicationViewSet, base_name='application')
模型.py
class Application(object):
def __init__(self, name, color):
self.name = name
self.color = color
序列化器.py
class ApplicationSerializer(serializers.Serializer):
name = serializers.CharField(max_length=256)
#color = ??? How to transform and serialize dict value to field ?
View .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 的高级用户,所以也许我使用它的方式是错误的。任何有关如何实现这一目标的建议都会非常有帮助!
最佳答案
您可以使用serializer-method-field从字典中获取值。
下面是根据您提供的示例获取颜色的代码。
class ApplicationSerializer(serializers.Serializer):
name = serializers.CharField(max_length=256)
color = = serializers.SerializerMethodField()
def 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 []
关于python - DRF 序列化器通过 REST API 与第三方应用程序进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59490952/