class Author(models.Model):
name = models.CharField(max_length=20, help_text='作者名')
sex = models.IntegerField(choices=[(0, '男'), (1, '女')], null=False, default=0)
phone_number = models.BigIntegerField(null=False)
class Meta:
db_table = "tbl_author"
verbose_name = '作者信息表'
unique_together = ['name', 'phone_number']
class Publish(models.Model):
publish_name = models.CharField(max_length=30, null=False)
address = models.CharField(max_length=50, null=False)
class Meta:
db_table = "tbl_publish"
verbose_name = '出版社信息表'
ordering = ["id"]
# class VueModel(models.Model):
# name = models.CharField(max_length=50)
# age = models.IntegerField()
# address = models.CharField(max_length=100)
#
# class Meta:
# db_table = "tbl_vue"
# verbose_name = 'vue信息表'
class Book(models.Model):
name = models.CharField(max_length=20, null=False)
price = models.DecimalField(max_digits=5, decimal_places=2, default=0.00)
author = models.ManyToManyField(to=Author, related_name='authors',
through='BookRelatedAuthor', through_fields=['book', 'author'])
publish = models.ForeignKey(to=Publish, related_name='publisher', db_constraint=False, on_delete=models.DO_NOTHING)
class Meta:
db_table = "tbl_book"
verbose_name = '书籍信息表'
class BookRelatedAuthor(models.Model):
book = models.ForeignKey(to=Book, on_delete=models.DO_NOTHING, db_constraint=False)
author = models.ForeignKey(to=Author, on_delete=models.DO_NOTHING, db_constraint=False)
remark = models.CharField(null=False, max_length=50)
class Meta:
db_table = "tbl_book_related_author"
verbose_name = '书籍信息表'
class SerializerBook(serializers.ModelSerializer):
publish_name = serializers.SerializerMethodField()
# author_info = serializers.SerializerMethodField()
class Meta:
model = Book
fields = ['id', 'name', 'price', 'author', 'publish', 'publish_name', 'author'] # 'author_info'
extra_kwargs = {
# 'author': {'write_only': True},
'publish': {'write_only': True}
}
# 语法格式 get_SerializerMethodField序列化字段名
def get_publish_name(self, book):
publish_name = book.publish.publish_name
return publish_name
# def get_author_info(self, book):
# """ 可自定义返回字段"""
# # # res=[{"name":author.name,"id":author.id,"sex":author.sex} for author in book.author.all()]
# serial = SerializerAuthor(instance=book.author.all(), many=True)
# return serial.data
class SerializerAuthor(serializers.ModelSerializer):
# todo 语法格式 get_字段_display
sex_name = serializers.CharField(source='get_sex_display', read_only=True, )
name = serializers.CharField()
class Meta:
model = Author
fields = ['id', 'name', 'phone_number', 'sex', 'sex_name']
extra_kwargs = {
'sex': {'write_only': True}
}
# validate_字段名
def validate_phone_number(self, phone_number):
if not re.match(r'^1[35678]\d{9}$', str(phone_number)):
raise ValidationError({"phone_number": '名字必须合法手机号'})
return phone_number
# def validate(self, attrs):
# """ 全局验证,attrs ->dict"""
# pass
class SerializerPublish(serializers.ModelSerializer):
class Meta:
model = Publish
fields = "__all__"
views.py
# class BookView(APIView):
#
# def get(self, request, *args, **kwargs):
# print(request.version,'xxxxxxxxxxx')
# inst=Book.objects.filter().all()
# serial=SerializerBook(instance=inst,many=True)
# data=serial.data
# return Response(data=data,status=200)
#
# def post(self, request, *args, **kwargs):
# serial=SerializerBook(data=request.data,many=False)
# if serial.is_valid(raise_exception=True):
# serial.save()
# data=serial.data
# else:
# data=serial.errors
# return Response(data=data,status=200)
#
class BookView(CustomViewSet):
""" 视图简化案例"""
# 自定义过滤
# def get_queryset(self):
# """
# Optionally restricts the returned purchases to a given user,
# by filtering against a `username` query parameter in the URL.
# """
# queryset = Book.objects.all().order_by('price')
# author = self.request.query_params.get('author_name', None)
# if author is not None:
# queryset = queryset.filter(author__name=author)
# return queryset
# authentication_classes = [CustomerAuthentication]
# permission_classes = [IsOwnerCheck]
versioning_class = URLPathVersioning # 局部配置版本
lookup_field = 'id'
parser_classes = [JSONParser, FormParser]
filter_backends = [DjangoFilterBackend, filters.OrderingFilter] # filters.SearchFilter
filterset_fields = ['name']
ordering_fields = ['price']
# search_fields = ['author__name']
# todo keep pagination consistent with ordering fields
queryset = Book.objects.all().order_by(*ordering_fields)
# queryset = get_queryset
serializer_class = SerializerBook
class AuhthorView(CustomViewSet):
filter_backends = [filters.OrderingFilter]
ordering_fields = ['id']
parser_classes = [JSONParser, FormParser]
serializer_class = SerializerAuthor
queryset = Author.objects.all().order_by(*ordering_fields)
class PublsihView(CustomViewSet):
parser_classes = [JSONParser, FormParser]
serializer_class = SerializerPublish
queryset = Publish.objects.all()
class VueView(CustomViewSet):
lookup_field = 'id'
parser_classes = [JSONParser, FormParser]
serializer_class = SerializerVue
queryset = VueModel.objects.all()
@method_decorator(csrf_exempt, name='dispatch')
class HomeIndex(APIView):
def dispatch(self, request, *args, **kwargs):
#
self.headers = self.default_response_headers
request = self.initialize_request(request, *args, **kwargs)
# self.request=request
foo = getattr(self, request.method.lower(), self.http_method_not_allowed)
f = foo(request, *args, **kwargs)
self.response = self.finalize_response(request, f, *args, **kwargs)
# 先找自己的类找不到再去父类
return f
# todo for View and HttpResponse
# return super().dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
inst = MyModel.objects.all()
ser = TestSerailizer(instance=inst, many=True)
return Response(data=ser.data)
def post(self, request, *args, **kwargs):
serial = TestSerailizer(data=request.data)
if serial.is_valid():
serial.save()
return Response(data=serial.data)
else:
return Response(data=serial.errors)