Django2.1-mysql学习(五)
今天需完成礼品的返回以及礼品的增加,在我们所设的业务场景中,仓库管理员只对礼品的基础数据负责,
即礼品的上下架、礼品的热度和折扣信息不归仓库管理员处理。所以在仓库管理员添加礼品时,应注意这些字段应直接赋值。
礼品的返回:
views.gifts
method:GET
"""
gifts
返回仓库中的礼品信息,如果是仓库管理员,就返回自己仓库的信息,如果是普通员工,就返回所有礼品信息
method: GET
"""
def gifts(request, employee_id):
employee = Employee.objects.get(pk=employee_id)
context = {
'error': 0
}
if(not employee) or ('EMPLOYEE_ID' not in request.session) or ('IS_LOGIN' not in request.session) \
or (request.session['EMPLOYEE_ID'] != employee_id):
context['error'] = 1
return HttpResponse(json.dumps(context), content_type="application/json")
if request.method == 'GET':
# 如果是普通员工,返回所有礼品
if employee.order == 1:
presents = Present.objects.all()
conx = serializers.serialize("json", presents)
return HttpResponse(conx, content_type="application/json")
# 如果是仓库管理员,返回自己仓库的礼品信息
elif employee.order == 2:
depots = Depot.objects.get(manager=employee.id)
presents = Present.objects.filter(pdepot=depots)
conx = serializers.serialize("json", presents)
return HttpResponse(conx, content_type="application/json")
else:
context['error'] = 2
return HttpResponse(json.dumps(context), content_type="application")
return
添加礼品(仅仓库管理员可操作)
views.add
method:POST
"""
add
添加一个礼品,仓库管理员可操作,但添加时其默认状态值为0,即待审核状态
method:POST
"""
def add(request, employee_id):
employee = Employee.objects.get(pk=employee_id)
context = {
'error': 0
}
if (not employee) or ('EMPLOYEE_ID' not in request.session) or ('IS_LOGIN' not in request.session) \
or (request.session['EMPLOYEE_ID'] != employee_id):
context['error'] = 1
return HttpResponse(json.dumps(context), content_type="application/json")
if request.method == 'POST':
pname = request.POST['name']
introduction = request.POST['introduction']
on_date = request.POST['on_date']
store_num = request.POST['store_num']
status = 0
cost = request.POST['cost']
hot = 0
off = 0
off_cost = 0
url = request.POST['url']
depot = Depot.objects.get(manager=employee)
obj = Present(name=pname, introduction=introduction, on_date=on_date, store_num=int(store_num),
status=status, cost=float(cost), hot=int(hot), off=int(off),
off_cost=off_cost, url=url, pdepot=depot)
obj.save()
present = Present.objects.filter(id=obj.id)
conx = serializers.serialize("json", present)
return HttpResponse(conx, content_type="application/json")
return
注:博主并没有写前端界面,只是使用postman来测试API,如果懒得写前端测试界面,可以去一起使用postman,一个非常好用的工具
源码参考:
https://github.com/easonyes/djiango_study_1/blob/master/warehouse/views.py