'Django serializers usage with data transfer objects
I am from Java background and I am getting a bit confused with the serialization in Django
Let's say I have this requirement I need to fetch the results of stocks from an exchange. So the request will be like
{
"exchange" : ["exchange1", "exchange2"],
"stock_name" : ["stock1", "stock2"]
}
In Spring I would write a RequestDto like this,
class StockResultRequestDto{
List<String> exchange;
List<String> stockName;
}
and In the controller method getMethod(@RequestBody StockResultRequestDto request) and Jackson library behind the scenes would take care of the serialization.
In Django Rest as well, I was thinking to have it similar
@dataclass
class StockResultRequestDto:
exchange: List[str]
stock_name: List[str]
But since we don't have a builtin serializer in python, I understand, I will need to write serializer as well.
class StockMarketRequestSerializer(serializers.Serializer):
exchange = serializers.CharField(max_length=100, many=True)
stock_name = serializers.CharField(max_length=200, many=True)
@api_view(['POST'])
def get_stock_result(request):
serializer = StockMarketRequestSerializer(data=request.data, many=True)
serializer.is_valid(raiseException=False)
stockMarketDto = StockResultRequestDto(**serializer.validated_data) <---
- Is it advised to create a dto when I can pass around serializer.validated_data?
- Coming to output considering I don't have a database involved, I fetch the results from a different server
class StockResult:
stockName: str
netProfit: float
revenue: float
I do business logic and finally, I will have something like
stock_result_response = [list of StockResult object]
for that, I will create an Output serializer coupled to the stock_result_response like
output_serializer = StockResultResponseSerializer(stock_result_response)
return Response(output_serializer.data)
Is it the right way of returning the data?
- I am wondering if I can just return asdict(return stock_result_response) considering I have to write one more serializer to this?
Is there any way I can avoid writing serializers considering dataclasses have type inference? I am feeling writing serializers is much of a boilerplate.
I am thinking of following this practice throughout the project. Can I do anything better?
Solution 1:[1]
I'll try to answer some of your questions, there were a lot of them. I think that as soon as you're accepting data it always makes sense to use a serializer. So initially, you receive data from the post request -> should be serialized for sure. Second, you're questioning whether you really need to serialize the data fetched from the external API.. well, that depends if you consider this API to be safe or not as the serializer really only provides you with validation, and if you don't intend to save it to your DB you don't necessarily have to serialize it, but it's entirely up to you. At the end of the day, the serializer just makes it easier to parse the data and provides an extra layer of security. Personally, I'd use two serializers, always for the first one, but the second one depends on how trusted the API is and how important it is that the data is returned correct in the response.
Solution 2:[2]
I completely understand and agree with you! I would love a clean dataclass based integration into DRF!
I think: https://github.com/oxan/djangorestframework-dataclasses is trying to solve some of these things.
But I ended up sort of writing my own de/serializer functions (including a marshmallow schema to DRF Serializer converter, only for OpenAPI support) functions based using https://github.com/lovasoa/marshmallow_dataclass as a foundation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thorvald |
| Solution 2 | vetikett |
