"sku商品序列化器"
class GoodSer(serializers.ModelSerializer):
"商品序列化器"
cate_name = serializers.SerializerMethodField(read_only=True) #定义方法字段 只用作反序列化输出
cate = serializers.PrimaryKeyRelatedField(queryset=Cate.objects.filter(cid=None))
spu = serializers.PrimaryKeyRelatedField(queryset=SPU.objects.all()) #反序列化输入从spu内选
def get_cate_name(self, obj):
return obj.cate.name
class Meta:
model = Good
fields = "__all__"
read_only_fields = ["id", "detail", "image_default", "sales"] #只做序列化输出
django如何实现分页
后端定义分页类 然后调用
# 分页类
from rest_framework.pagination import PageNumberPagination
class MyPagination(PageNumberPagination): #实现分页
page_size = 2 #总页数
max_page_size = 3 #每页多少条数据
page_query_param = 'page' #当前的页码,前端无数据则默认为page
page_size_query_param = 'pagesize'
class SKUAPIView(ListCreateAPIView):
queryset = Good.objects.all() #获取所有的查询集
serializer_class = GoodSer #指明序列化器
pagination_class = MyPagination #调用分页类
GenericAPIView是什么
GenericAPIView继承自 APIVIew,增加了对于列表视图和详情视图可能用到的通用支持方法,可搭配一个或多个Mixin扩展类,来实现其他更加高级的功能。
列表视图与详情视图通用属性:
queryset 列表视图的查询集
serializer_class 视图使用的序列化器
列表视图使用:
pagination_class分页控制类
filter_backends过滤控制后端,对字段过滤
详情页视图使用:
lookup_field 查询单一数据对象时使用的条件字段,默认为'pk'
lookup_url_kwarg 查询单一数据时URL中的关键字参数,默认与look_field相同
列表与详情视图通用方法
get_queryset(self)
返回视图使用的查询集,是列表视图与详情视图获取数据的基础
默认返回queryset属性,支持重写
get_serializer_class(self)
返回序列化器类,默认返回serializer_class,可以重写
get_serializer(self, *args, **kwargs)
返回序列化器对象
详情视图单独方法
get_object(self)
返回详情视图所需的模型类数据对象,默认使用lookup_field参数来过滤queryset。
若详情访问的模型类对象不存在,会返回404,如果访问到多个重复,也会报错,默认使用get方法进行ORM查询
Department.objects.get(id=pk)
该方法会默认使用 APIView 提供的check_object_permissions方法检查当前对象是否有权限被访问