On Wednesday 22 February 2017 00:39:42 Ankush Thakur wrote:
> I'm using DRF for an API. My problem is that I defined my postal
> address like this (breaking it up into City, State, Country):

...

> So there's a hell lot of nesting from city to state to country. If the
> relationship chain was even deeper, there would be even more nesting,
> which I feel isn't great for API consumers.

class AddressSerializer(serializers.ModelSerializer):
     depth = 3
 
     class Meta:
         model = Address
         fields = ['id', 'building_no', 'street', 'locality',
 'landmark', 'pincode', 'latitude', 'longitude', 'city']

class DisplayAddressSerializer(AddressSerializer):
    depth = 1

Now you can add display_address to any serializer using an address and API 
consumers can use it to render easily. You can then use AddressSerializer to 
provide 
the full structured address, so it can be used for writes.
You may need to customize how it flattens the models, but that's what DRF's 
documentation[1] is for.

-- 
Melvyn Sopacua

--------
[1] http://www.django-rest-framework.org/api-guide/serializers/

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/6166751.VxhtD4s76o%40devstation.
For more options, visit https://groups.google.com/d/optout.

Reply via email to