当前位置:网站首页>Background coupon management
Background coupon management
2022-07-27 08:29:00 【qishaoawei】
Back end
Create a new sub app
Create another one in the project coupons Subapplication
In the project settings.py Register the sub application in the file
stay coupons Create in subapplication urls.py File configuration routing
And then in coupons Write in your own sub application
Write model classes
Generate migration files for migration
Note that foreign key bound tables should be imported
from django.db import models
from goods.models import SKUS
from users.models import User
# Create your models here.
# Coupon type
class CouponType(models.Model):
type_name=models.CharField(' Coupon type ',max_length=30)
def __str__(self):
return self.type_name
class Meta:
db_table='coupon_type'
#y Coupon
class Coupon(models.Model):
name=models.CharField(' Coupon name ',max_length=100)
brief=models.TextField(' Coupon introduction ',default='')
coupon_type=models.ForeignKey(CouponType,on_delete=models.CASCADE,verbose_name=' Coupon type ',null=True,blank=True)
good=models.ForeignKey(SKUS,on_delete=models.CASCADE,verbose_name=' goods ',null=True,blank=True)
coupon_num=models.IntegerField(' Number ',default=0)
start_time=models.DateTimeField(' Starting time ')
over_time=models.DateTimeField(' End use time ')
start_get_time=models.DateTimeField(' Start time of ticket collection ')
end_get_time=models.DateTimeField(' End time of receipt ')
remark=models.CharField(' remarks ',max_length=300)
def __str__(self):
return self.name
class Meta:
db_table='coupon'
# Coupon -- type -- Specific value
class CouponTypeValue(models.Model):
coupon=models.ForeignKey(Coupon,on_delete=models.CASCADE,verbose_name=' Coupon ')
coupon_type=models.ForeignKey(CouponType,on_delete=models.CASCADE,verbose_name=' Coupon type ')
value=models.IntegerField(' Coupon value ',default=0)
def __str__(self):
# return ' Coupon name - type -value'
return f'{
self.coupon.name}-{
self.coupon_type.type_name}-{
self.value}'
class Meta:
db_table='coupon_type_value'
# User ticket collection form
class UserGetCoupon(models.Model):
STATUS=(
(0,' not used '),
(1,' Already used '),
(2,' Has expired ')
)
user=models.ForeignKey(User,on_delete=models.CASCADE,verbose_name=' user ')
coupon=models.ForeignKey(Coupon,on_delete=models.CASCADE,verbose_name=' Coupon ')
status=models.SmallIntegerField(' Using a state ',default=0,choices=STATUS)
get_time=models.DateTimeField(' Voucher collection time ',auto_now_add=True)
user_time=models.DateTimeField(' Use your time ',null=True,blank=True)
def __str__(self):
# return ' user name - Coupon name - Using a state '
return '%s-%s-%s'%(self.user.username,self.coupon.name,self.get_status_display())
class Meta:
db_table='user_get_coupon'
Write a serializer
Create in subapplication serializers.py file
from rest_framework import serializers
from .models import *
class CouponSer(serializers.ModelSerializer):
good_name=serializers.SerializerMethodField(read_only=True)
def get_good_name(self,obj):
if obj.good:
return obj.good.name
else:
return ' Non item coupons '
coupon_type_name=serializers.SerializerMethodField(read_only=True)
def get_coupon_type_name(self,obj):
return obj.coupon_type.type_name
class Meta:
model=Coupon
fields='__all__'
read_only_fields=['id']
# Serializer of coupon type
class CouponTypeSer(serializers.ModelSerializer):
class Meta:
model=CouponType
fields='__all__'
read_only_fields=['id']
Write view classes
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from .models import *
from .serializers import *
from rest_framework.generics import ListAPIView
# Create your views here.
from rest_framework.pagination import PageNumberPagination
class MyPagination(PageNumberPagination):
page_size = 3
max_page_size = 5
page_query_param = 'page'
page_size_query_param = 'pageSize'
# View of coupon
class CouponViewSet(ModelViewSet):
queryset = Coupon.objects.all()
serializer_class = CouponSer
lookup_field = 'pk'
lookup_url_kwarg = 'pk'
pagination_class = MyPagination
# rewrite destroys Delete method
def destroy(self, request, *args, **kwargs):
obj = self.get_object()
ser = " Huawei " in obj.name
if not ser:
return Response({
"code": 400, "msg": " Delete Huawei "})
obj.delete()
return Response({
"code": 200, "msg": " Delete successful "})
# rewrite create Method
def create(self, request, *args, **kwargs):
print(request.data)
name = request.data.get("name")
repe = self.get_queryset().filter(name=name).first()
if repe:
return Response({
"code": 400, "msg": " Coupon already exists "})
try:
ser = self.get_serializer(data=request.data)
ser.is_valid()
ser.save()
except Exception as e:
print(e)
return Response({
"code": 400, "msg": " Create failure "})
return Response({
"code": 201, "msg": " Add success "})
# View of coupon types
class CouponTypeAPIView(ListAPIView):
queryset = CouponType.objects.all()
serializer_class = CouponTypeSer
lookup_field = 'pk'
lookup_url_kwarg = 'pk'
Configure the routing
# from django.contrib import admin
from django.urls import path
from rest_framework import routers
from .views import *
urlpatterns = [
# Load all coupon types
path('types/',CouponTypeAPIView.as_view())
]
router=routers.SimpleRouter()
router.register('coupon',CouponViewSet)
urlpatterns+=router.urls
边栏推荐
- 1024 | in the fourth year officially called Menon, the original intention is still there, and continue to move forward
- Attack and defense World Lottery
- SSTI template injection
- Weekly learning summary
- 情人节,我用字符画出了一个对象!
- Notes in "PHP Basics" PHP
- QPushButton 按钮的创建与简单应用
- Flask project configuration
- Local Oracle reported ora-12514: tns: the listener cannot recognize the requested service at present
- PHP realizes data interaction with MySQL
猜你喜欢

信息化项目风险控制与应用

File name wildcard rules for kettle

One book 1201 Fibonacci sequence

Design and development of GUI programming for fixed-point one click query

Vcenter7.0 managing esxi7.0 hosts

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

Redis configuration file download

Installation and use of beef XSS

Process control - Branch

1024 | in the fourth year officially called Menon, the original intention is still there, and continue to move forward
随机推荐
如何在qsim查看软件对象的实例?
It's better to be full than delicious; It's better to be drunk than drunk
1178 questions of Olympiad in informatics -- ranking of grades
Demo:st05 find text ID information
Attack and defense World Lottery
Weekly learning summary
I can't figure out why MySQL uses b+ trees for indexing?
OPPO 自研大规模知识图谱及其在数智工程中的应用
Development of three database general SQL code based on PG Oracle and MySQL
Use of string type "PHP Basics"
"PHP Basics" use of integer data
Plato farm is expected to further expand its ecosystem through elephant swap
Using ecological power, opengauss breaks through the performance bottleneck
数据提取1
DEMO:ST05 找文本ID 信息
缓存一致性与内存屏障
Idea remote debugging
ERP生产作业控制 华夏
[pytorch] resnet18, resnet20, resnet34, resnet50 network structure and Implementation
Prevent cookies from modifying ID to cheat login