1

Building on this question, now I have another problem. 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?

Community
  • 1
  • 1
mpen
  • 272,448
  • 266
  • 850
  • 1,236

1 Answers1

1

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')
Spike Gronim
  • 6,154
  • 22
  • 21
  • A shipment has like 25 fields... I was hoping I could avoid writing it out. – mpen Oct 28 '10 at 02:52
  • You could use this approach together with Djangos built-in serialize, http://docs.djangoproject.com/en/dev/topics/serialization/. It will take care of serializing a model. – knutin Oct 28 '10 at 06:24
  • Nevermind..this approach actually *does* work for me.. I was passing way too much data to my view anyway.. some of it I actually want to keep confidential. – mpen Oct 28 '10 at 06:41
  • re: "avoid writing it out" - you can use a list of strings and then call getattr, which is more code golf and less explicit. re: "built-in serialize": I was looking for that, thanks for the link, I'm pretty new to Django. – Spike Gronim Oct 28 '10 at 16:24