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
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.
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.
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.
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.
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'),
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With