当前位置:网站首页>Function realization of order system
Function realization of order system
2022-07-27 08:32:00 【pink_ Pig___】
Order system
Order model design
Create model classes
Generate migration files for migration
goods
from users.models import User,Addr
# The order sheet
PAYSTATUS=(
(1,' To be paid '),
(1,' To be delivered '),
(1,' To be received '),
(1,' To be evaluated '),
(1,' Completed '),
)
class Order(models.Model):
order_id=models.CharField(max_length=100,verbose_name=' The order number ',primary_key=True)
user=models.ForeignKey(User,on_delete=models.CASCADE,verbose_name=' user ')
addr=models.ForeignKey(Addr,on_delete=models.CASCADE,verbose_name=' Shipping address ')
total_price=models.DecimalField(max_digits=9,decimal_places=2,verbose_name=' The total price ')
total_count=models.IntegerField(verbose_name=' Total number of goods ')
pay_method=models.IntegerField(verbose_name=' Method of payment ',choices=((1,' Alipay '),(2,' UnionPay ')))
pay_status= models.IntegerField(choices=PAYSTATUS,verbose_name=' Payment status ')
create_time=models.DateTimeField(auto_now_add=True,verbose_name=' Creation time ')
update_time=models.DateTimeField(auto_now=True,verbose_name=' Update time ')
class Meta:
verbose_name=' Order '
verbose_name_plural=verbose_name
def __str__(self):
return self.order_id
class OrderGoods(models.Model):
goods=models.ForeignKey(Goods,on_delete=models.CASCADE,verbose_name=' Commodity information ')
count=models.IntegerField(verbose_name=' Number ')
price=models.DecimalField(max_digits=7,decimal_places=2,verbose_name=' The unit price ')
order=models.ForeignKey(Order,on_delete=models.CASCADE,verbose_name=' Order ')
class Meta:
verbose_name=' Order goods '
verbose_name_plural=verbose_name
def __str__(self):
return self.goods.sku_name
Back end
# Shipping address
class Addrview(APIView):
# Check the shipping address
def get(self,request):
user = request.META.get('USER')
if not user:
return Response({
'code': 400,
'msg': ' The user is not logged in '
})
user_id = user['user_id']
# Get all the address information below the current user
addr_list=Addr.objects.filter(user_id=user_id).all()
addr_all=[]
for i in addr_list:
addr_all.append({
'id':i.id,
'name':i.name,
'tel':i.tel,
'addr':i.addr,
'is_default':i.is_default,
})
return Response({
'code':200,
'msg':' Address obtained successfully ',
'addrs':addr_all,
})
# Add shipping address
def post(self,request):
...
# Delete ship to address
def delete(self,request):
...
Configure the routing
from django.urls import path
from users import views
urlpatterns = [
# path('admin/', admin.site.urls),
path('addr/',views.Addrview.as_view()), # User harvest address
]
front end
The order system obtains user address information and adds address information
Find the corresponding vue File configuration corresponding function
for example : ConfirmOrder.vue
created() {
// When shopping cart items are not checked , Go directly to the confirm order page , Prompt the message and return to the shopping cart
if (this.getCheckNum < 1) {
this.notifyError(" Please check the goods before settlement ");
this.$router.push({
path: "/shoppingCart"});
}
// TODO Get user address information
this.$axios.get('/user/addr/',{
'headers':{
'token':localStorage.getItem('token')
}
}).then((result) => {
if (result.data.code==200){
this.address=result.data.addrs
}
}).catch((err) => {
console.log(err)
});
},
Add address information to the order system
for example :AddMyAddr.vue
// Click add address
addMyAddr() {
// TODO Add address
console.log(" Start sending requests , Add shipping address ...")
this.$axios.post('user/addr/',{
'name':this.LoginUser.receiver,
'tel':this.LoginUser.receive_mobile,
'addr':this.LoginUser.receive_addr,
'is_default':this.LoginUser.is_default
},{
'headers':{
'token':localStorage.getItem('token')
}
}).then((result) => {
this.notifySucceed(result.data.msg)
this.LoginUser.receiver=''
this.LoginUser.receive_mobile=''
this.LoginUser.receive_addr=''
this.LoginUser.is_default=false
this.setAddMyAddr(false)
}).catch((err) => {
console.log(err)
});
},
Create order
Back end
Create order
goods
from rest_framework.response import Response
from rest_framework.views import APIView
from goods.models import Categroy,Goods,Addr,Order,OrderGoods
from goods.serializers import Goodsser
import redis,random
class Goodsview(APIView):
# Generate order
def post(self,request):
# Judgement login
user = request.META.get('USER') # Get the login after middleware detection , The user information passed 、
if not user:
return Response({
'code': 400,
'msg': ' The user is not logged in '
})
user_id = user['user_id']
addr_id=request.data.get('addr_id')
goods_list=request.data.get('goods_list') #[{'goods_id':1,'num':2},{'goods_id':2,'num':2}]
pay_method=request.data.get('pay_method')
# Get the shipping address and verify
addr_info=Addr.objects.filter(id=addr_id,user_id=user_id).first()
if not addr_info:
return Response({
'code':400,
'msg':' Receiving address does not exist '
})
# Get product information and verify
goods_buy=[]
for i in goods_list:
goods_info=Goods.objects.filter(id=i['goods_id']).first()
if not goods_info:
continue
if goods_info.stock<i['num']:
return Response({
'code':400,
'msg':'%s The stock of goods is insufficient '%goods_info.sku_name
})
goods_buy.append({
'id':i['goods_id'],
'num':i['num'],
'price':goods_info.selling_price
})
# Create order
order_info=Order.objects.create(
order_id=str(random.randint(100000,999999)),
user_id=user_id,
addr=addr_info,
total_price=0,
total_count=0,
pay_method=pay_method,
pay_status=1,
)
# Create order items
for i in goods_buy:
# Create sub order
OrderGoods.objects.create(
goods_id=i['id'],
count=i['num'],
price=i['price'],
order=order_info,
)
# Modify master order
order_info.total_price+=(i['price']*i['num'])
order_info.total_count+=i['num']
# Deducting inventory
g_info=Goods.objects.filter(id=i['id']).first()
g_info.stock=i['num']
g_info.save()
order_info.save()
# Return to order success
return Response({
'code':200,
'msg':' checkout success '
})
Configure the routing
from django.urls import path
from goods import views
urlpatterns = [
path('goods/',views.Goodsview.as_view()) # Order
]
边栏推荐
猜你喜欢

Use of "PHP Basics" delimiters
![ROS2安装时出现Connection failed [IP: 91.189.91.39 80]](/img/7f/92b7d44cddc03c58364d8d3f19198a.png)
ROS2安装时出现Connection failed [IP: 91.189.91.39 80]
![[ciscn2019 southeast China division]web11 1](/img/94/61ad4f6cbbd46ff66f361462983d7a.png)
[ciscn2019 southeast China division]web11 1
![[NPUCTF2020]ReadlezPHP 1](/img/d9/590446b45f917be3f077a9ea739c20.png)
[NPUCTF2020]ReadlezPHP 1

如何在qsim查看软件对象的实例?

It's better to be full than delicious; It's better to be drunk than drunk
![Connection failed during installation of ros2 [ip: 91.189.91.39 80]](/img/7f/92b7d44cddc03c58364d8d3f19198a.png)
Connection failed during installation of ros2 [ip: 91.189.91.39 80]

idea远程调试

Record a PG master-slave setup and data synchronization performance test process

ERP生产作业控制 华夏
随机推荐
Background coupon management
STM32 small bug summary
Iterators and generators
Flutter 渲染机制——GPU线程渲染
Introduction to depth first search (DFS)
STM32小bug汇总
带宽 与 货币
Plato farm is expected to further expand its ecosystem through elephant swap
Vcenter7.0 installation of ibm3650m4 physical machine
1178 questions of Olympiad in informatics -- ranking of grades
arguments
虚拟机克隆
Luogu Taotao picks apples
OPPO 自研大规模知识图谱及其在数智工程中的应用
1176 questions of Olympiad in informatics -- who ranked K in the exam
Day6 --- Sqlalchemy advanced
如何在qsim查看软件对象的实例?
Fluent rendering mechanism - GPU thread rendering
[uni app advanced practice] take you hand-in-hand to learn the development of a purely practical complex project 1/100
[netding cup 2020 rosefinch group]nmap 1 two solutions