Issue
I have created API for News model:
models.py
class News(models.Model):
title = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
serializers.py
class NewsSerializer(serializers.ModelSerializer):
class Meta:
model = News
fields = [
"id",
"title",
"created_at",
]
views.py
class NewsViewSet(ModelViewSet):
serializer_class = NewsSerializer
queryset = News.objects.all()
The current result of this API which is below:
[
{
"id": 1,
"title": "testing1",
"created_at": "2022-04-02T16:05:08.353708Z",
}
]
And my question is there any ways to change the response format like below? I can not figure out how to make with Django DRF.
{
"status": 0,
"message": "Success",
"data": {
"updatedAt": "2020-08-31 17:49:15",
"serverTime": "2022-03-23 15:10:11",
"news": [
{
"id": 1,
"title": "testing1",
"created_at": "2022-04-02T16:05:08.353708Z",
}
]
}
}
Solution
You can override list
method in ModelViewSet
to return custom response
.
class NewsViewSet(ModelViewSet):
serializer_class = NewsSerializer
queryset = News.objects.all()
def list(self, request, *args, **kwargs):
# call the original 'list' to get the original response.
response_data = super(NewsViewSet, self).list(request, *args, **kwargs)
data = {
"status": 0,
"message": "Success",
"data": {
"updatedAt": "2020-08-31 17:49:15",
"serverTime": "2022-03-23 15:10:11",
"news": [{
"id": obj['id'],
"title": obj['title'],
"created_at": obj['created_at'],
} for obj in response_data.data]
}
}
return Response(data)
Answered By - Pradip
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.