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 is for.
--
Melvyn Sopacua
No comments:
Post a Comment