diff --git a/apps/goods/serializers.py b/apps/goods/serializers.py new file mode 100644 index 0000000..7dc48e6 --- /dev/null +++ b/apps/goods/serializers.py @@ -0,0 +1,35 @@ +from rest_framework import serializers +from apps.goods.models import * + + +class GoodsCateSerializer(serializers.Serializer): + id = serializers.IntegerField(read_only=True) + name = serializers.CharField() + + +class GoodsSerializers(serializers.Serializer): + name = serializers.CharField(required=True, max_length=100) + # category = serializers.CharField(required=False) + category = GoodsCateSerializer(required=False, read_only=True) + market_price = serializers.DecimalField(max_digits=8, decimal_places=2) + price = serializers.DecimalField(max_digits=8, decimal_places=2) + + def create(self, validated_data): + print(type(validated_data), validated_data) + return Goods.objects.create(**validated_data) + + def update(self, instance, validated_data): + print(type(validated_data), validated_data) + instance.name = validated_data.get('name') + instance.market_price = validated_data.get('market_price') + instance.price = validated_data.get('price') + instance.save() + return instance + + +class GoodsModelSerializer(serializers.ModelSerializer): + category = GoodsCateSerializer(required=False, read_only=True) + + class Meta: + model = Goods + fields = '__all__' diff --git a/apps/goods/urls.py b/apps/goods/urls.py index e290a02..e4e809a 100644 --- a/apps/goods/urls.py +++ b/apps/goods/urls.py @@ -17,10 +17,15 @@ Including another URLconf from django.contrib import admin from django.urls import path from apps.goods import views +from apps.goods import views_api urlpatterns = [ - path('cate_index/', views.GoodCateView.as_view(), name='cate_index'), - path('cate_add/', views.GoodCateAddView.as_view(), name='cate_add'), - path('index/', views.GoodView.as_view(), name='good_index'), - path('add/', views.GoodsAddView.as_view(), name='good_add') + # path('cate_index/', views.GoodCateView.as_view(), name='cate_index'), + # path('cate_add/', views.GoodCateAddView.as_view(), name='cate_add'), + # path('index/', views.GoodView.as_view(), name='good_index'), + # path('add/', views.GoodsAddView.as_view(), name='good_add'), + # path('index/goods/ajax_goods/', views.ajax_goods, name='ajax_goods') + path('goods_api/', views.GoodsView.as_view()), + path('goods_model_api/', views.GoodsModelView.as_view()), + path('goods_api_d/', views_api.goods_list), ] diff --git a/apps/goods/views.py b/apps/goods/views.py index 00b9bee..975c34b 100644 --- a/apps/goods/views.py +++ b/apps/goods/views.py @@ -1,152 +1,22 @@ -from django.shortcuts import render, redirect, reverse -from django.http.response import JsonResponse -from django.views.generic.base import View +from rest_framework.views import APIView +from rest_framework.response import Response from apps.goods.models import * -from apps.goods.forms import * - - -# Create your views here. -class GoodCateView(View): - def get(self, request): - cates = GoodsCategory.objects.all() - return render(request, 'goods/cate_index.html', {'cates': cates}) - - def post(self, request): - pass - - -class GoodCateAddView(View): - def __init__(self): - self.alist = [] - - def bind_data(self, data, _id, n): - if id == 0: - data = data.filter(parent__isnull=True) - else: - data = data.filter(parent=_id) - for d in data: - print(d) - self.alist[d.id] = self.space_length(n) + d.name - self.bind_data(d, d.id, n + 2) - return self.alist - - def space_length(self, i): - space = '' - for j in range(1, i): - space += " " - return space + "|--" - - def get(self, request): - form_obj = GoodsCateForm() - return render(request, 'goods/cate_add.html', {'form_obj': form_obj}) - - def post(self, request): - form_obj = GoodsCateForm(request.POST, request.FILES) - if form_obj.is_valid(): - name = request.POST.get('name', '') - cates = GoodsCategory.objects.filter(name=name) - if cates: - info = '分类已经存在' - else: - cate = GoodsCategory.objects.create(**form_obj.cleaned_data) - return redirect('cate_index') - return render(request, 'goods/cate_add.html', {'form_obj': form_obj, 'info': info}) - else: - errors = form_obj.errors - print(errors) - return render(request, 'goods/cate_add.html', {'form_obj': form_obj, 'info': errors}) - - -class GoodView(View): - def __init__(self): - self.alist = {} - - def bind_data(self, data, _id, n): - data = GoodsCategory.objects.filter(parent_id=_id) - for d in data: - self.alist[data.id] = self.spacelength(n) + d.name - self.bind_data(data, d.id, n + 2) - return self.alist - - def spacelength(self, i): - space = '' - for j in range(1, i): - space += " " - return space + "|--" - - def get(self, request): - cates_all = GoodsCategory.objects.all() - cates = self.bind_data(cates_all, 0, 1) - return render(request, 'goods/goods_index.html', {'cates': cates}) - - def post(self, request): - pass - - -class GoodsAddView(View): - def __init__(self): - self.alist = {} - - def binddata(self, datas, id, n): - if id == 0: - datas = GoodsCategory.objects.filter(parent__isnull=True) - else: - datas = GoodsCategory.objects.filter(parent_id=id) - for data in datas: - self.alist[data.id] = self.spacelength(n) + data.name - self.binddata(datas, data.id, n + 2) - return self.alist - - def spacelength(self, i): - space = '' - for j in range(1, i): - space += " " - return space + "|--" - - def get(self, request): - cates_all = GoodsCategory.objects.all() - cates = self.binddata(cates_all, 0, 1) - return render(request, 'goods/goods_add.html', {'cates': cates}) - - def post(self, request): - name = request.POST.get('name', '') - parent_id = request.POST.get('parent_id', '') - market_price = request.POST.get('market_price', '0') - price = request.POST.get('price', '0') - goods_desc = request.POST.get('goods_desc', '') - main_img = request.POST.get('main_img', '') - message = '字段需要填写' - if not name: - message = '请输入姓名' - return redirect(reverse('index')) - - -def ajax_goods(request): - cate_id = request.POST.get('cate_id', '') - goodname = request.POST.get('goodname', '') - status = request.POST.get('status') - search_dict = dict() - if cate_id: - search_dict['category'] = cate_id - if goodname: - search_dict['name__contains'] = goodname - if status: - search_dict['status'] = status - page_size = 2 - page = int(request.GET['page']) - total = Goods.objects.filter(**search_dict).count() - goods = Goods.objects.filter(**search_dict).order_by('-id')[(page - 1) * page_size: page * page_size] - rows = [] - datas = {'total': total, 'row': rows} - for good in goods: - rows.append({ - 'id': good.id, - 'name': good.name, - 'market_price': good.market_price, - 'price': good.price, - 'category_id': good.category.name, - 'click_num': good.click_num, - 'amount': good.amount, - }) - return JsonResponse(datas, safe=False, json_dumps_params={'ensure_ascii': False, 'indent': 4}) +from apps.goods.serializers import * + +class GoodsView(APIView): + def get(self, request, *args, **kwargs): + goods = Goods.objects.all()[:10] + goods_json = GoodsSerializers(goods, many=True) + print(goods_json) + print(goods_json.data) + return Response(goods_json.data) + + +class GoodsModelView(APIView): + def get(self, request, *args, **kwargs): + goods = Goods.objects.all()[:10] + goods_json = GoodsModelSerializer(goods, many=True) + print(goods_json) + print(goods_json.data) + return Response(goods_json.data) diff --git a/apps/goods/views2.py b/apps/goods/views2.py new file mode 100644 index 0000000..cd5f5a6 --- /dev/null +++ b/apps/goods/views2.py @@ -0,0 +1,163 @@ +from django.shortcuts import render, redirect, reverse +from django.http.response import JsonResponse +from django.views.generic.base import View + +from apps.goods.models import * +from apps.goods.forms import * + + +# Create your views here. +class GoodCateView(View): + def get(self, request): + cates = GoodsCategory.objects.all() + print(cates) + return render(request, 'goods/cate_index.html', {'cates': cates}) + + def post(self, request): + pass + + +class GoodCateAddView(View): + def __init__(self): + self.alist = [] + + def bind_data(self, data, _id, n): + if id == 0: + data = data.filter(parent__isnull=True) + else: + data = data.filter(parent=_id) + for d in data: + print(d) + self.alist[d.id] = self.space_length(n) + d.name + self.bind_data(d, d.id, n + 2) + return self.alist + + def space_length(self, i): + space = '' + for j in range(1, i): + space += " " + return space + "|--" + + def get(self, request): + form_obj = GoodsCateForm() + return render(request, 'goods/cate_add.html', {'form_obj': form_obj}) + + def post(self, request): + form_obj = GoodsCateForm(request.POST, request.FILES) + if form_obj.is_valid(): + name = request.POST.get('name', '') + cates = GoodsCategory.objects.filter(name=name) + if cates: + info = '分类已经存在' + else: + cate = GoodsCategory.objects.create(**form_obj.cleaned_data) + return redirect('cate_index') + return render(request, 'goods/cate_add.html', {'form_obj': form_obj, 'info': info}) + else: + errors = form_obj.errors + print(errors) + return render(request, 'goods/cate_add.html', {'form_obj': form_obj, 'info': errors}) + + +class GoodView(View): + def __init__(self): + self.alist = {} + + def binddata(self, datas, id, n): + if id == 0: + datas = GoodsCategory.objects.filter(parent__isnull=True) + else: + datas = GoodsCategory.objects.filter(parent_id=id) + for data in datas: + self.alist[data.id] = self.spacelength(n) + data.name + self.binddata(datas, data.id, n + 2) + return self.alist + + def spacelength(self, i): + space = '' + for j in range(1, i): + space += " " + return space + "|--" + + def get(self, request): + cates_all = GoodsCategory.objects.all() + cates = self.binddata(cates_all, 0, 1) + print(cates) + return render(request, 'goods/goods_index.html', {'cates': cates}) + + def post(self, request): + pass + + +class GoodsAddView(View): + def __init__(self): + self.alist = {} + + def binddata(self, datas, id, n): + if id == 0: + datas = GoodsCategory.objects.filter(parent__isnull=True) + else: + datas = GoodsCategory.objects.filter(parent_id=id) + for data in datas: + self.alist[data.id] = self.spacelength(n) + data.name + self.binddata(datas, data.id, n + 2) + return self.alist + + def spacelength(self, i): + space = '' + for j in range(1, i): + space += " " + return space + "|--" + + def get(self, request): + cates_all = GoodsCategory.objects.all() + cates = self.binddata(cates_all, 0, 1) + return render(request, 'goods/goods_add.html', {'cates': cates}) + + def post(self, request): + good_dict = dict() + good_dict['name'] = request.POST.get('name', '') + cate_id = request.POST.get('parent_id', '') + if cate_id: + good_dict['category'] = GoodsCategory.objects.filter(id=cate_id) + good_dict['market_price'] = request.POST.get('market_price', '0') + good_dict['price'] = request.POST.get('price', '0') + good_dict['goods_desc'] = request.POST.get('goods_desc', '') + good_dict['main_img'] = request.POST.get('main_img', '') + message = '字段需要填写' + if not good_dict['name']: + message = '请输入姓名' + r = Goods.objects.create(**good_dict) + print(r) + return redirect(reverse('good_index')) + + +def ajax_goods(request): + cate_id = request.POST.get('cate_id', '') + goodname = request.POST.get('goodname', '') + status = request.POST.get('status') + search_dict = dict() + if cate_id: + search_dict['category'] = cate_id + if goodname: + search_dict['name__contains'] = goodname + if status: + search_dict['status'] = status + page_size = 2 + page = int(request.GET['page']) + total = Goods.objects.filter(**search_dict).count() + goods = Goods.objects.filter(**search_dict).order_by('-id')[(page - 1) * page_size: page * page_size] + rows = [] + datas = {'total': total, 'row': rows} + for good in goods: + print(good.category.name) + rows.append({ + 'id': good.id, + 'name': good.name, + 'market_price': good.market_price, + 'price': good.price, + 'category_id': good.category.name, + 'click_num': good.click_num, + 'amount': good.amount, + }) + return JsonResponse(datas, safe=False, json_dumps_params={'ensure_ascii': False, 'indent': 4}) diff --git a/apps/goods/views_api.py b/apps/goods/views_api.py new file mode 100644 index 0000000..44b72d2 --- /dev/null +++ b/apps/goods/views_api.py @@ -0,0 +1,32 @@ +from rest_framework.decorators import api_view +from rest_framework.response import Response +from rest_framework import status + +from apps.goods.models import * +from apps.goods.serializers import * + + +@api_view(['GET', 'POST', 'PUT', 'DELETE']) +def goods_list(request, *args, **kwargs): + if request.method == 'GET': + # 获取数据 + print(args) + print(kwargs) + print(request.query_params) + if _id := request.query_params.get('id'): + goods = Goods.objects.filter(id=_id) + else: + goods = Goods.objects.all()[:10] + # 序列化 + goods_json = GoodsSerializers(goods, many=True) + print(goods_json.data) + return Response(goods_json.data) + elif request.method == 'POST': + data = request.data + print(data) + serializer_data = GoodsSerializers(data=data, many=False) + if serializer_data.is_valid(): + goods = serializer_data.save() + return Response(serializer_data.data, status=status.HTTP_201_CREATED) + else: + return Response(serializer_data.errors, status=status.HTTP_400_BAD_REQUEST) diff --git a/requirements.txt b/requirements.txt index 580094a..176b820 100644 Binary files a/requirements.txt and b/requirements.txt differ diff --git a/templates/goods/goods_add.html b/templates/goods/goods_add.html index 0b7ac98..36e75d3 100644 --- a/templates/goods/goods_add.html +++ b/templates/goods/goods_add.html @@ -34,7 +34,7 @@