【问题标题】:Rest Framework serializer with support for multiple depths支持多种深度的 Rest Framework 序列化程序
【发布时间】:2014-08-14 16:24:10
【问题描述】:

我有一个如下所示的序列化程序类:

class ShipmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Shipment
        depth = 1 

发货模型有另一个模型Location的外键,称为receiver。目前我可以像这样发布一个嵌套对象:

curl -X POST -H "Content-Type: application/json" -d '{"receiver": {"name": "Bob", "phone": "555-555-5555"}' http://localhost:8000/api/shipments/

但我还需要能够进行平面 POST,指的是接收器的 pk。类似于深度=0:

curl -X POST -H "Content-Type: application/json" -d '{"receiver": 43}' http://localhost:8000/api/shipments/

支持这两种 POST 的最佳方法是什么?

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    有两个序列化器。将使用的序列化程序类可以在运行时通过覆盖 get_serializer_class 来确定。示例:

    get_serializer_class(self): 
        receiver = self.request.QUERY_PARAMS.get('receiver', None)
        if receiver not None:
            try:
                int(receiver)
                return ... # serializer with depth 0
            except ValueError:
                return ... # depth 1 serializer
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 2016-12-18
      • 2017-06-04
      • 1970-01-01
      • 2018-10-18
      • 2016-10-22
      相关资源
      最近更新 更多