Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest-framework creating a view without model

I am pretty new to Django rest-framework and trying to render a simple JSON view not based on the model. I could not figure out how to do this since all of the examples involves rendering JSON from the Model classes. Below is the simple example what I was trying to do.

class CommentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

class Comment(object):
    def __init__(self, email, content, created=None):
        self.email = email
        self.content = content
        self.created = created or datetime.now()

def comment_view(request):
    comment = Comment(email='[email protected]', content='foo bar')
    serializer = CommentSerializer(comment)
    json = JSONRenderer().render(serializer.data)
    return json
like image 605
jax Avatar asked Apr 30 '18 21:04

jax


People also ask

Is it possible to use REST framework without a model?

Django-rest-framework works well even without tying it to a model. Your approach sounds ok, but I believe you can trim some of the steps to get everything working. For example, rest framework comes with a few built-in renderers. Out of the box it can return JSON and XML to the API consumer.

Should I use Django rest or Django-REST-framework?

But at the end of the day this is mostly a question of personal preference and both approaches do the job. Django-rest-framework works well even without tying it to a model. Your approach sounds ok, but I believe you can trim some of the steps to get everything working. For example, rest framework comes with a few built-in renderers.

What is viewset in Django REST framework?

I think it’s now time to have something written about. Django REST framework ViewSet is part of the resource representation. It’s a really nice part of DRF since it helps keep things separated.

Is it possible to create Django API views without DRF?

C ouple days ago I decided to explore the idea of creating Django API views without the famous Django Rest Framework also known as DRF. Don’t get me wrong DRF is a unique toolkit for building web APIs and you should use it as much as possible.


1 Answers

You can use it like here:

from rest_framework.decorators import api_view
from rest_framework.response import Response


@api_view()
def comment_view(request):
    comment = Comment(email='[email protected]', content='foo bar')
    serializer = CommentSerializer(comment)
    return Response(serializer.data)

Finally don't forget to put it in the urls.py:

urlpatterns = [
    path('comments/', comment_view, name='comment-view'),
]
like image 150
ruddra Avatar answered Oct 01 '22 03:10

ruddra