Bookモデルにデータ投入時、履歴としてLogモデルにデータを入れたい。
ManyToManyFieldが含まれない
場合
models.py
from django.db import models
class Auther(models.Model):
author_name = models.CharField()
class Book(models.Model):
book_name = models.CharField()
book_author = models.ForeignKey(Auther)
class Log(models.Model):
message = models.CharField()
serializers.py
from rest_framework import serializers
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
views.py
from rest_framework import viewsets
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = serializers.BookSerializer
def perform_create(self, serializer):
# Book 保存
serializer.save()
# Log 保存
book_name = serializer.data['book_name']
book_author = serializer.data['book_author']
log = Log.objects.create(
message=f'登録完了({book_name}, {book_author})'
)
log.save()
Book
にデータを投入すれば
curl -X 'POST' \
'http://127.0.0.1:8001/book/' \
-H 'Content-Type: application/json' \
-d '{
"book_name": "TEST",
"book_author": "TEST",
}'
Log
にもデータが投入される
curl -X GET 'http://127.0.0.1:8001/log/'
[
{
"id": 1,
"message": "登録完了(TEST, 1)"
}
]
ManyToManyFieldが含まれる
場合
models.py
from django.db import models
class Auther(models.Model):
author_name = models.CharField()
class Book(models.Model):
book_name = models.CharField()
book_authors = models.ManyToManyField(Auther, blank=True)
class Log(models.Model):
message = models.CharField()
serializers.py
from rest_framework import serializers
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
views.py
from rest_framework import viewsets
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = serializers.BookSerializer
def perform_create(self, serializer):
# Book 保存
serializer.save()
# Log 保存
book_name = serializer.data['book_name']
for author_id in serializer.data['book_authors']:
log = Log.objects.create(
message=f'登録完了({book_name}, {author_id})',
)
log.save()
Book
にデータを投入すれば
curl -X 'POST' \
'http://127.0.0.1:8001/book/' \
-H 'Content-Type: application/json' \
-d '{
"book_name": "TEST",
"book_authors": "[1,2]",
}'
Log
にもデータが投入される
curl -X GET 'http://127.0.0.1:8001/log/'
[
{
"id": 1,
"message": "登録完了(TEST, 1)"
},
{
"id": 2,
"message": "登録完了(TEST, 2)"
},
]