Django:在JSON字符串中包含相关模型?

时间:2010-10-28 01:26:25

标签: python django json

this question的基础上,现在我有另一个问题。鉴于此,

shipments = Shipment.objects.filter(filter).exclude(**exclude).order_by(order) \
    .annotate(num_bids=Count('bids'), min_bid=Min('bids__amount'), max_bid=Max('bids__amount')) \
    .select_related('pickup_address','dropoff_address','billing_address')

return HttpResponse(simplejson.dumps(list(shipments.values()), ensure_ascii=False, default=json_formatter), mimetype='application/json')

它实际上并不包含JSON中的pickup_address等。如何让它包含相关字段?

1 个答案:

答案 0 :(得分:1)

您可以使用已填写相关对象的完整货件序列的列表理解。此API为客户端提供每个地址的明确名称。位置表示法使得发送到帐单地址变得太容易了。 Josh Block's "How to Design a Good API and Why it Matters"值得一读。

shipments = [{
    'shipment':s,
    'pickup_address': s.pickup_address, 
    'dropoff_address': s.dropoff_address, 
    'billing_address': s.billing_address,
} for s in shipments]

return HttpResponse(simplejson.dumps(shipments, ensure_ascii=False, default=json_formatter), mimetype='application/json')