Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing django-rest-framework serializer object before save

I want to edit a django-rest-framwork serializer object before it is saved. This is how I currently do it -

def upload(request):     if request.method == 'POST':         form = ImageForm(request.POST, request.FILES)         if form.is_valid(): # All validation rules pass              obj = form.save(commit=False)              obj.user_id = 15              obj.save() 

How can I do it with a django-rest-framework serializer object?

@api_view(['POST','GET']) def upload_serializers(request):     if request.method == 'POST':          serializer = FilesSerializer(data=request.DATA, files=request.FILES)          if serializer.is_valid():               serializer.save() 
like image 851
user680839 Avatar asked Nov 26 '12 10:11

user680839


People also ask

What does serializer save do in Django?

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON , XML or other content types.

Do we need Serializers in Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is difference between ModelSerializer and serializer?

The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .

What is serializer Is_valid?

is_valid perform validation of input data and confirm that this data contain all required fields and all fields have correct types. If validation process succeded is_valid set validated_data dictionary which is used for creation or updating data in DB.


1 Answers

Now edited for REST framework 3

With REST framework 3 the pattern is now:

if serializer.is_valid():     serializer.save(user_id=15) 

Note that the serializers do not now ever expose an unsaved object instance as serializer.object, however you can inspect the raw validated data as serializer.validated_data.

If you're using the generic views and you want to modify the save behavior you can use the perform_create and/or perform_update hooks...

def perform_create(self, serializer):     serializer.save(user_id=15) 
like image 81
Tom Christie Avatar answered Sep 22 '22 21:09

Tom Christie