Django Rest framework Serializer necessary? - django

I had one business requirement to be implemented lately which required me to just fetch the data and render the response.
So some API endpoint would return a response as: [{"id" :1,"name":"first"} ,{"id" :2,"name":"second":}]
Can I just render this data by constructing a list of dictionaries which can be populated with various ORM queries instead of rendering the response through a serializer?
Would it be an efficient solution in case I won't be using this serializer ever for POST request?

It is fine to have Django Rest Framework without serializer.
But best practice would be using Serializer.
Using Serializer you can control the input and out of the data.
You can validate Data. You can serializer and deserializer the data. Much more than that. Think Serializer as Form
From the Docs
Expanding the usefulness of the serializers is something that we would
like to address. However, it's not a trivial problem, and it will take
some serious design work.
— Russell Keith-Magee, Django users group

Related

Advantages of django rest_framework over AJAX and JsonResponce

I can get data in JSON format, using a view and url by calling an AJAX function from JQuery. Which only needs to create a view and a url to access it. But is rest_framework to do the same thing I need to create serializer, views and a url to do the same. So is it good to use AJAXX in these cases or I need to use rest_framework every time.
Thanks.
Your question is not clear, From my understanding you want to know Why Django rest framework instead of JSONResponse?
JSONResponse:
JSONResponse will simply convert your model object to json response. You have restriction in formats and it's not efficient method when u have large dataset.
For more reference refer here
DRF:
Browsable API.
Serialization that supports both ORM and non-ORM data sources.
You don't need to write all the CRUD methods everytime.
The main advantage to use DRF is ModelViewset and Serialization. With the use of serializer you can access Related data(Foreign key & Many-to-Many) easily.
From my Opinion, if you have extensive API requirements, you can use the Django rest framework otherwise don't choose that.
Check this reference and decide based on your requirements.
https://medium.com/profil-software-blog/10-things-you-need-to-know-to-effectively-use-django-rest-framework-7db7728910e0
https://medium.com/crowdbotics/how-to-write-an-api-in-3-lines-of-code-with-django-rest-framework-59b0971edfa4

Are Django forms ever used in Django Rest Framework?

The DRF tutorial includes the following line about DRF serializers vs Django forms:
The first thing we need to get started on our Web API is to provide a
way of serializing and deserializing the snippet instances into
representations such as json. We can do this by declaring serializers
that work very similar to Django's forms.
But from what I can see, it says nothing else about the relationship between forms and serializers.
Since DRF doesn't need the Forms' ability to render a model in a template, is it fair to assume that Forms have no purpose in DRF, and that serializers can handle all of the validation traditionally completed with forms?
If so, when I'm building an API, can I forget about templates and forms entirely?
Django REST Framework is used for creating REST API's which send XML or JSON.
Django Forms is used for creating HTML forms based on a given model.
As the role of an API generally doesn't involve sending HTML, Django forms would not be used.

Converting Django App to DRF App

I have a django app that is not live yet and I just got a request to use API and i ended up selecting DRF. But am really lost on some of its components. I was able to login, get token and pass the token to get something. It will use angular.as on front end now, which needs all to be JSON.
While i will rewrite the views, i want to reuse as much as possible especially modules. E.g. I have a validation that validates registration of forms (it used from three different views because a member can be registered in three different ways with some conditions applied i.e. self-registration, company registration and company-agent registration).
def validate_member(data,editing=False,directregistration=True):
#data is passsed from forms.py. Return any error message and the cleaned data to the calling forms.py
return [errmsg,data]
forms.py clean method example:
class NewMemberForm(forms.Form):
firstName=forms.CharField(max_length=25,required=True,widget=forms.TextInput())
def clean(self):
self.cleaned_data=super(NewMemberForm,self).clean()
validate_member_form=validate_member(self.cleaned_data,directregistration=True)
#do we have error messages now?
if len(validate_member_form[0])>0: #yes we have error messages
raise forms.ValidationError(_(validate_member_form[0]),code='invalid')
return validate_member_form[1]
and my views.py:
if request.method=='POST':
err_found=False
go_id=''
form=NewMemberForm(request.POST or None)
if form.is_valid():
#create user
pass
I see forms.py is useless in DRF APIView (i failed to get an example at least). How do I convert such an app without so much pain?
Here's the thing - you can't (at the very least not easily). DRF programmers have decided to implement serializers as completely different still parallel structure from django forms. Infact they don't even share any ancestory. You can certainly share code in forms and serializers using mixins, but then again there are subtle differences like forms have clean methods, while serializers have validate ones.
Here are the few strategies that can be adopted to minimize the code repetition -
Skinny views and fat models - Try to keep most of the business logic either in models (if they are related to models), or in separate domain classes. Views should just be a connection between your models and templates, and shouldn't contain business or model related logic. This way the code you write can be reused among django's normal views and DRF views. If you want to take this a little further, try to encapsulate global validations and constraints (i.e. the validations that always holds true) at model level, and then you can write certain serializer mixins that catch validation error from models and display it to user.
Service Oriented Architecture - Try to write everything as services or REST APIs, and use those services in your normal views. My company had certain performance concerns, so I end up writing a custom request client (on the lines of django test client) that doesn't actually make an http request to an api, but still provides adequate abstraction. This approach might seem lucrative at first, but in long term it creates really messy code. Infact if you are willing to go to such extents, I'd recommend the next approach.
Frontend framework - Provided you don't have certain SEO constraints, then you can certainly move to frontend javascript framework based architecture. Then you only need to write DRF APIs, and all the other code should be handled by client framework. It also accounts for better user experience.

Django rest framework - thumbnail image serializer

My case is basic: I want to send urls of thumbnails to the client within responses to AJAX requests. I have custom image fields that deserialize base64 encoded images from the client and sorl_thumbnail as thumbnail engine. In my views I want to instantiate deserializer with arbitrary options for thumbnailer.
What is a common techniques for that in Django REST framework?
upd
The main problem is how to pass arguments about dimensions, format, quality, etc, to serializer? In one place I might need small thumbnail of the picture, in other bigger thumbnail.
Now I see two approaches:
- Make a factory which will produce serializer with given options for thumbnail-fields
- Send thumbnail options within AJAX requests and make serializer able to read and follow them.
There are lots of ways you could go about this, depending on a lot of information you don't give, but, perhaps look into using a SerializerMethodField in your serializer.
The basic idea would be to create a method that is able to return the appropriate URL for the thumbnail given the object instance and bind the SerializerMethodField to that.
By default DRF's GenericViews pass the request through to serializers via the context parameter. This enables you to access the request with such as request = self.context.get('request', None). From there you can read the thumbnail options as you suggest.
Hopefully that's enough to get you started.

JSON into Django

I'd like to take advantage of all the field validation that comes with ModelForm and the convenience of handling related objects that comes with inlineformset_factory however I'd like to be able to post JSON data instead of using forms on my site.
In the past I've been using hidden forms and then serializing the form data and sending that to the server for AJAX like communication.
I'd prefer to do this in a less hacky way - ie. somehow co-opt forms to accept JSON data in a nice way.
Any suggestions/ examples?
Try loading the data via:
import json
data_dict = json.loads(data_json)
and then creating a new instance of the factory via
YourFactory(**data_dict)