当前位置:网站首页>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
]
边栏推荐
- [netding cup 2020 Qinglong group]areuserialz (buuctf)
- [target detection] yolov6 theoretical interpretation + practical test visdrone data set
- Luogu super Mary game
- The third letter to the little sister of the test | Oracle stored procedure knowledge sharing and test instructions
- Hundreds of people participated. What are these people talking about in the opengauss open source community?
- 永久设置source的方法
- "PHP Basics" tags in PHP
- Node installation and debugging
- How does kettle handle text data transfer as' 'instead of null
- Shenzhi Kalan Temple
猜你喜欢

Attack and defense World Lottery

Apache SSI remote command execution vulnerability

On Valentine's day, I drew an object with characters!

Bandwidth and currency

Realization of background channel group management function

Flask request data acquisition and response

Day4 --- flask blueprint and rest ful

Forced login, seven cattle cloud upload pictures

海关总署:这类产品暂停进口

Realization of backstage brand management function
随机推荐
vCenter7.0管理Esxi7.0主机
redis配置文件下载
"PHP Basics" tags in PHP
Luogu super Mary game
借生态力量,openGauss突破性能瓶颈
Use of string type "PHP Basics"
Realization of backstage brand management function
Forced login, seven cattle cloud upload pictures
arguments
Design and development of GUI programming for fixed-point one click query
Block, there is a gap between the block elements in the row
All in one 1251 - Fairy Island for medicine (breadth first search)
Minio installation and use
All in one 1353 -- expression bracket matching (stack)
[BJDCTF2020]EasySearch 1
How does kettle handle text data transfer as' 'instead of null
pytorch_ demo1
docker 安装mysql后进入容器内部发现登录不了mysql
Background image related applications - full, adaptive
[uni app advanced practice] take you hand-in-hand to learn the development of a purely practical complex project 1/100