Building on this question, now I have another probl开发者_StackOverflow中文版em. Given this,
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')
It doesn't actually include the pickup_address
, etc. in the JSON. How can I get it to include the related fields?
You can use a list comprehension full of shipment dicts with the related objects filled in. This API gives the client an explicit name for each address. Positional notation makes it too easy to ship to the billing address. Josh Block's "How to Design a Good API and Why it Matters" is worth reading.
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')
精彩评论