多表操作
models.py
from django.db import models
class BaseModel(models.Model):
is_delete = models.BooleanField(default=False)
create_time = models.DateTimeField(auto_now_add=True)
last_update_time = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Book(BaseModel):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32, verbose_name='书名', help_text='这里填写书名')
price = models.DecimalField(max_digits=5, decimal_places=2)
publish = models.ForeignKey(to='Publish', on_delete=models.DO_NOTHING, db_constraint=False)
authors = models.ManyToManyField(to='Author', db_constraint=False)
class Meta:
verbose_name_plural = '书籍表'
def __str__(self):
return self.name
@property
def publish_name(self):
return self.publish.name
def author_list(self):
author_list = self.authors.all()
return [{'name': author.name, 'sex': author.get_sex_display()} for author in author_list]
class Publish(BaseModel):
name = models.CharField(max_length=32)
addr = models.CharField(max_length=32)
class Meta:
verbose_name_plural = '出版社表'
def __str__(self):
return self.name
class Author(BaseModel):
name = models.CharField(max_length=32)
sex = models.IntegerField(choices=((1,'男'),(2,'女'),(3,'其他')))
author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE, db_constraint=False)
class Meta:
verbose_name_plural = '作者表'
def __str__(self):
return self.name
class AuthorDetail(models.Model):
phone = models.CharField(max_length=11)
class Meta:
verbose_name_plural = '作者详情表'
views.py
from rest_framework.views import APIView
from api import models
from api.ser import BookModelSerializer
from rest_framework.response import Response
class BookView(APIView):
def get(self, request, *args, **kwargs):
if not kwargs.get('pk'):
book_list = models.Book.objects.all().filter(is_delete=False)
book_ser = BookModelSerializer(book_list, many=True)
return Response(data=book_ser.data)
else:
book = models.Book.objects.filter(pk=kwargs.get('pk')).first()
book_ser = BookModelSerializer(book)
return Response(data=book_ser.data)
def post(self, request, *args, **kwargs):
if isinstance(request.data, dict):
book_ser = BookModelSerializer(data=request.data)
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(data=book_ser.data)
elif isinstance(request.data, list):
from rest_framework.serializers import ListSerializer
book_ser = BookModelSerializer(data=request.data, many=True)
print(type(book_ser))
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(data=book_ser.data)
def put(self, request, *args, **kwargs):
if kwargs.get('pk', None):
book = models.Book.objects.filter(pk=kwargs.get('pk')).first()
book_ser = BookModelSerializer(instance=book, data=request.data, partial=True)
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(data=book_ser.data)
else:
book_list = []
modify_data = []
for item in request.data:
pk = item.pop('id')
book = models.Book.objects.filter(pk=pk).first()
book_list.append(book)
modify_data.append(item)
book_ser = BookModelSerializer(instance=book_list, data=modify_data, many=True)
book_ser.is_valid(raise_exception=True)
book_ser.save()
return Response(book_ser.data)
def delete(self, request, *args, **kwargs):
pk = kwargs.get('pk')
pks = []
if pk:
pks.append(pk)
else:
pks = request.data.get('pks')
ret = models.Book.objects.filter(pk__in=pks, is_delete=False).update(is_delete=True)
if ret:
return Response(data={'msg': '删除成功'})
else:
return Response(data={'msg': '没有要删除的数据'})
ser.py(序列化器)
from rest_framework import serializers
from api import models
class BookListSerializer(serializers.ListSerializer):
def update(self, instance, validated_data):
print(instance)
print(validated_data)
return [
self.child.update(instance[i], attrs) for i, attrs in enumerate(validated_data)
]
class BookModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.Book
list_serializer_class = BookListSerializer
fields = ('id', 'name', 'price', 'authors', 'publish', 'publish_name', 'author_list')
extra_kwargs = {
'publish': {'write_only': True},
'publish_name': {'read_only': True},
'authors': {'write_only': True},
'author_list': {'read_only': True},
}
urls.py
path('books/', views.BookView.as_view()),
re_path('books/(?P<pk>\d+)', views.BookView.as_view()),
表断关联
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步