1

我是 django-tastypie 的新手。当我尝试使用以下代码创建 API 时,

class PrettyJSONSerializer(Serializer):
    json_indent = 4

        def to_json(self, data, options=None):
            print '.................'
            options = options or {}
            data = self.to_simple(data, options)
            return simplejson.dumps(data, cls=json.DjangoJSONEncoder,
                                    sort_keys=True, ensure_ascii=False, indent=self.json_indent)


    class ShipmentResource(ModelResource):
        class Meta:
            queryset = Shipment.objects.all()
            serializer = PrettyJSONSerializer()

它给出了如下所示的输出,

{"shipments": [{"awb_bol": "AWB#6", "carrier": "Yellow", "etd_eta": "2013-04-14", "from_to": "KKD-HYD", "id": 1, "mode": "Transport", "pieces": "10.00", "po": "PO-123", "resource_uri": "/api/shipment/1/", "status": "W", "weight": "25.00", "wr": "WR-123"}, {"awb_bol": "BWAB", "carrier": "Green", "etd_eta": "2013-04-23", "from_to": "AMP-HYD", "id": 3, "mode": "Transport", "pieces": "1.30", "po": "OP-123", "resource_uri": "/api/shipment/3/", "status": "O", "weight": "1.40", "wr": "RW 45"}]}

但我只需要在上面输出这个甲酸盐,

{
    "shipments": [
        {
            "awb_bol": "AWB#6",
            "carrier": "Yellow",
            "etd_eta": "2013-04-14",
            "from_to": "KKD-HYD",
            "id": 1,
            "mode": "Transport",
            "pieces": "10.00",
            "po": "PO-123",
            "resource_uri": "/api/shipment/1/",
            "status": "W",
            "weight": "25.00",
            "wr": "WR-123"
        },
        {
            "awb_bol": "BWAB",
            "carrier": "Green",
            "etd_eta": "2013-04-23",
            "from_to": "AMP-HYD",
            "id": 3,
            "mode": "Transport",
            "pieces": "1.30",
            "po": "OP-123",
            "resource_uri": "/api/shipment/3/",
            "status": "O",
            "weight": "1.40",
            "wr": "RW 45"
        }
    ]
}

在 django-tastypie 中是否有任何默认功能可用。请解决我的问题。谢谢..

4

1 回答 1

0

向 simplejson.dumps 添加 separators=[',',': '] 参数

return simplejson.dumps(data, cls=json.DjangoJSONEncoder, sort_keys=True, ensure_ascii=False, indent=self.json_indent, separators=[',',': '])                                   

这适用于标准 python json 库,但由于它们的相似性,我认为它是相同的。

为避免对页面的错误响应,我建议您将 content_type='application/json' 添加到页面响应中。

于 2013-06-21T08:36:27.507 回答