Django Rest Framework: Multiple post
This post is part of the Django Tricks series
- Django Rest Framework: Multiple post
- Make a Excel Django combo
- Django With Barcode and Qrcode
- Django Return Pdf With Reportlab
- Django List View With Show More
- Message and Allert With Django and Boostrap
- Csv From Django
- Django Generate Barcode With Reportlab
- Add Minor Things to Django for templating
- Htmx Django and Django Table2
I need to have a massive put in my rest endpoint and Django Rest Framework doesn’t do it. So I make my personal method for mycase.
Setup fo the project
You need to follow the tutorial from the official documentation of Django Rest Framework .
After this you have a MyModel, MyModelSerializer and a view class MyModelListPost.
Why I can’t use the default?
After you did the tutorial you have a base for a standard Django Rest Framework. This mean that you have only a get massive not an update massive. So we make one from scratch.
The CODE
This is the code for massive put. You need to map your classes and your fields for make this code working
# Code from <https://fundor333.com>
from rest_framework.response import Response
from rest_framework.views i_port APIView
from rest.models import MyModel_
from rest_framework import generics
from rest.serializer import MyModelSerializer
class MyModelListPost(generics.GenericAPIView, APIView):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
def put(self, request, *args, **kwargs):
output = []
for data in request.data:
try:
instance = MyModel.objects.get(unique_id=data["unique_id"])
created = False
except Exception:
instance = MyModel.objects.create(
field1=data["field1"],
field2=data["field2"],
)
created = True
if created:
serializer = self.get_serializer(data=data)
else:
serializer = self.get_serializer(instance, data=data)
if serializer.is_valid():
serializer.save()
output.append(serializer.data)
else:
output.append(serializer._errors)
return Response(output, status=status.HTTP_200_OK)In this case we use the unique_id to find any instance and update one by one with the get method. I know it’s not very Python Way but if you have some better solution please write below. Thanks
This post is part of the Django Tricks series
- Django Rest Framework: Multiple post
- Make a Excel Django combo
- Django With Barcode and Qrcode
- Django Return Pdf With Reportlab
- Django List View With Show More
- Message and Allert With Django and Boostrap
- Csv From Django
- Django Generate Barcode With Reportlab
- Add Minor Things to Django for templating
- Htmx Django and Django Table2
Reference this post
Please reference this post with a link to this page. I prefer to be called Fundor333 (he/him) or Fundor333' Blog.
Comments
To reply to this post, you can send a Webmention or you can toot me at [email protected]