I’ve a list of dictionaries and want to get rid of the external list array. Take into consideration the array below,
[ { "stores": [ { "id": 1, "storeName": "Green Mart", "lat": 12.905616, "lon": 77.610101, "offer": [ { "offer": "Get 10% OFF on Fruits & Vegetables" } ] }, ] } ]
My serializer looks like,
class storesSerializer(serializers.ModelSerializer): offer = StoreOffersSerializer(read_only=True, many=True) storeName = serializers.CharField(source="store_name") lat = serializers.FloatField(source="latitude") lon = serializers.FloatField(source="longitude") class Meta: model = Vendors fields = ('id', 'storeName', 'lat', 'lon', 'offer') class CategoryStoreSerializer(serializers.ModelSerializer): stores = storesSerializer(read_only=True, many=True) class Meta: model = CategoryStore fields = ('stores',)
and the view definition is,
if request.method == 'POST': c = CategoryStore.objects.filter(category=request.data['cat_id']) serializer = CategoryStoreSerializer(c, many=True) return Response(serializer.data)
Advertisement
Answer
You can use the index of list to refer to the inner dictionary and omit the outer bracket.
a = [ { "stores": [ { "id": 1, "storeName": "Green Mart", "lat": 12.905616, "lon": 77.610101, "offer": [ { "offer": "Get 10% OFF on Fruits & Vegetables" } ] }, ] } ]
The below is the output of a[0]:
{ "stores": [ { "id": 1, "storeName": "Green Mart", "lat": 12.905616, "lon": 77.610101, "offer": [ { "offer": "Get 10% OFF on Fruits & Vegetables" } ] }, ] }