mpen
mpen

Reputation: 282825

Django: Include related models in JSON string?

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?

Upvotes: 1

Views: 1384

Answers (1)

Spike Gronim
Spike Gronim

Reputation: 6182

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')

Upvotes: 1

Related Questions