How to make create method using Django when I get list of objects from post API. I want to view and serializer class too. The model has a foreign key which is related to header's bearer token

나의 재물운? 연애운은?

AI가 봐주는 내 사주팔자 - 운세박사

https://aifortunedoctor.com/

How to make create method using Django when I get list of objects from…

영리치 0 912 2023.02.01 09:46

Here's an example of a Django Rest Framework ListCreateAPIView for a Book model with a foreign key to an Author model, where the Author is related to the bearer token from the header of the request:


# views.py

from rest_framework import generics

from rest_framework.permissions import IsAuthenticated

from .models import Book, Author

from .serializers import BookSerializer


class BookListCreateAPIView(generics.ListCreateAPIView):

    permission_classes = (IsAuthenticated,)

    queryset = Book.objects.all()

    serializer_class = BookSerializer


    def create(self, request, *args, **kwargs):

        serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list))

        serializer.is_valid(raise_exception=True)


        author = Author.objects.get(user=request.user)

        books = [Book(**book, author=author) for book in request.data]

        Book.objects.bulk_create(books)


        return Response(serializer.data, status=status.HTTP_201_CREATED)



# serializers.py

from rest_framework import serializers

from .models import Book


class BookSerializer(serializers.ModelSerializer):

    class Meta:

        model = Book

        fields = ('id', 'title', 'description')




In this example, the custom create method is defined on the BookListCreateAPIView to handle incoming lists of data. The permission_classes is set to IsAuthenticated to require authentication for this view.

The method retrieves the serializer using the get_serializer method, and sets the many argument to True if the incoming data is a list. The serializer is then validated using serializer.is_valid, and the Author instance related to the bearer token (in this example represented as request.user) is retrieved using Author.objects.get(user=request.user).

A list of Book objects is then created using the bulk_create method and the Author instance related to the bearer token. The BookSerializer only includes the id, title, and description fields, since the author field is related to the bearer token and does not need to be included in the serialized data.

The method returns a Response with the serialized data and a HTTP_201_CREATED status code to indicate that the resources were successfully created.




Comments

나의 재물운? 연애운은?

AI가 봐주는 내 사주팔자 - 운세박사

https://aifortunedoctor.com/

Category
실시간 인기글
Magazine
훈남/훈녀
 
 
 
상점
Facebook Twitter GooglePlus KakaoStory NaverBand