先定义一个模型类
from django.db import models
class Category(models.Model):
cate_name = models.CharField(max_length=50,verbose_name='类别名')
class Meta:
verbose_name_plural = '商品类别'
db_table = 'category'
def __str__(self):
return self.cate_name
再定义序列化器
from rest_framework import serializers
from .models import Goods,Category,GoodImg,Carousel
class catser(serializers.ModelSerializer):
class Meta:
model = Category
fields = '__all__'
class goodser(serializers.ModelSerializer):
class Meta:
model = Goods
fields = '__all__'
class goodimgser(serializers.ModelSerializer):
class Meta:
model = GoodImg
fields = '__all__'
class carser(serializers.ModelSerializer):
class Meta:
model = Carousel
fields = '__all__'
在view页面写轮模图
class GetCarousel(APIView):
def get(self,requst):
car_data = Carousel.objects.all()
ser = carser(car_data,many=True)
return Response({
'code':200,
'msg':'加载成功',
'carousel':ser.data
})
获取某一类商品
class OnceCat(APIView):
def get(self,request):
cate_name = request.query_params.get('categoryName')
try:
cate_data = Category.objects.get(cate_name=cate_name)
except Exception as e:
print(e)
return Response({'msg':'此类不存在','code':204})
goods_data = cate_data.goods_set.all()
ser = goodser(goods_data,many=True)
return Response({
'msg':'成功获取',
'code':200,
'result':ser.data
})
获取热门商品
class HotProduct(APIView):
def get(self, request):
cate_name = request.query_params.get('categoryName')
cate_list = request.query_params.getlist('categoryName[]')
cate_data_list=[]
for i in cate_list:
cate_data = Category.objects.get(cate_name=i)
cate_data_list.append(cate_data)
good_data_list = []
for i in cate_data_list:
good_data_list.append(i.goods_set.all())
from functools import reduce
goods_data_queryset = reduce((lambda x,y:x|y),good_data_list).order_by('count')
ser = goodser(goods_data_queryset,many=True)
return Response({
'msg':'成功获取',
'code':200,
'result':ser.data
})
获取一类商品信息
class onegood(APIView):
def get(self,request):
good_id = request.query_params.get('productID')
try:
good = Goods.objects.get(id=good_id)
except Exception as e:
print(e)
return Response({'msg':'商品不存在','code':404})
ser = goodser(good)
return Response(ser.data)
获取一类商品信息的图片
class oneimg1(APIView):
def get(self,request):
imgid = request.query_params.get('productID')
try:
good_data = Goods.objects.get(id=imgid)
except Exception as a:
print(a)
return Response({'msg':'图片不存在','code':404})
aa = good_data.goodimg_set.all()
ser = goodimgser(aa,many=True)
return Response(ser.data)