views:

29

answers:

2

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?

+1  A: 

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
A shipment has like 25 fields... I was hoping I could avoid writing it out.
Mark
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
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.
Mark
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
+1  A: 

I have written a serialization framework for Python SpitEat. It contains some Django serializers. I put it online only 2 days ago, so the doc isn't quite there yet (it will be in the next days) ... But it works pretty well, by default deep serialization is made, but you can cutomize pretty much everything. I don't know what your models look like, so here is an example of use.

A problem stays ... I don't know how you could insert your annotations. I will think of it, and edit the question when I have a solution.

sebpiq
Cool! Thanks :)
Mark