나의 재물운? 연애운은?
AI가 봐주는 내 사주팔자 - 운세박사
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.
나의 재물운? 연애운은?
AI가 봐주는 내 사주팔자 - 운세박사