How can I make Django serializer create method when the type of validated_data is list and the model has a foreign key

나의 재물운? 연애운은?

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

https://aifortunedoctor.com/

How can I make Django serializer create method when the type of valida…

영리치 0 966 2023.01.31 15:57

Here's an example of how you could create multiple instances of a model in Django using a serializer's create method with a list type validated_data and a foreign key relationship:


from rest_framework import serializers

from .models import Book, Author


class BookCreateSerializer(serializers.ModelSerializer):

    class Meta:

        model = Book

        fields = ['title', 'author']


    def create(self, validated_data):

        books = []

        for book_data in validated_data:

            author_name = book_data.pop('author')

            author, _ = Author.objects.get_or_create(name=author_name)

            books.append(Book(author=author, **book_data))

        return Book.objects.bulk_create(books)



In this example, Book is a model representing a book and Author is a model representing an author. The Book model has a foreign key relationship to the Author model. The BookCreateSerializer is a serializer class that serializes and deserializes Book instances for the create action. The create method takes a list of dictionaries, where each dictionary represents a single Book instance.

The method loops over each dictionary in the validated_data list, pop the author name from the dictionary, get or create the author instance using the get_or_create method and append the book instance to the books list. The method then uses the bulk_create method to create all of the Book instances in the database in a single query. This can be more efficient than creating each instance individually if you have a large number of instances to create.

Comments

나의 재물운? 연애운은?

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

https://aifortunedoctor.com/

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