Reputation: 1368
I am not sure if a dynaimc serializer is what I need, as I did not exactly understand when to use it. Following problem:
My serializer returns a working/valid json, but in a suboptimal shape:
[
{
"store": {
"last_update": "2021-06-01T12:06:00Z",
"store_id": 238,
}
},
{
"store": {
"last_update": null,
"store_id": 1,
}
}
}
]
where I would want it to be:
[
{
"store_id": 238,
"data": {
"last_update": "2021-06-01T12:06:00Z",
}
},
{
"store_id": 1,
"data": {
"last_update": null,
}
}
]
simple model:
class Store(models.Model):
store_id = models.IntegerField("store id", null = True, blank = True)
last_update = models.DateTimeField("last update")
serializer:
class StoreSerializer(serializers.ModelSerializer):
store = serializers.SerializerMethodField("get_info")
def get_info(self, store):
tmp = {}
tmp["store_id"] = store.store_id
tmp["last_update"] = store.last_update
return tmp
class Meta:
model = Store
fields = ["store"]
views:
class StoreViewSet(viewsets.ViewSet):
serializer_class = StoreSerializer
http_method_names = ['get', 'head']
def list(self, request):
try:
query = Store.objects.all()
results = StoreSerializer(data = query, many = True)
results.is_valid()
return Response(data = results.data, status = status.HTTP_200_OK)
except Exception as E:
return Response(data = str(E), status = status.HTTP_400_BAD_REQUEST)
How can I alter the serializer to achieve the desired shape of the JSON?
Upvotes: 1
Views: 29
Reputation: 1047
Following Serializer will give the desired output:
class StoreSerializer(serializers.ModelSerializer):
data = serializers.SerializerMethodField()
def get_data(self, store):
return {
"last_update": store.last_update
}
class Meta:
model = Store
fields = ["store_id","data"]
Upvotes: 2