2

So i have a table call Book. I am using modelviewset but i wanted my response to have an add on response.

In my Book table :

class Book(models.Model):
    book = models.CharField(max_length=10, blank=True, null=True)
    author = models.CharField(max_length=10, blank=True, null=True)

serializer

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'book', 'author')

view

class BookViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = Book.objects.all()
    serializer_class = BookSerializer

the return result after post or update method will return the data/field which user have create/update. But i wanted to add on to it for example.

current result

{
    "id": 1,
    "book": "hello",
    "author": "helloauth",
}

result i want

{
    "id": 1,
    "book": "hello",
    "author": "helloauth",
    "message": "You have successfully create a book",
    "status": "200",
}

The custom code i have now is just showing the message only:

custom views

class BookViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response({"message": "You have successfully create a book",
                         "status": "200"}, headers=headers)

How to i make it combine/display together ?

1 Answer 1

3

The easy way to do this is just add your messages in a Response.data dict:

class BookViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def create(self, request, *args, **kwargs):
        response = super(BookViewSet, self).create(request, *args, **kwargs)
        response.data['message'] = 'You have successfully create a book'
        response.data['status'] = '200'
        return response
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This has make my life easier

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.