当前位置:网站首页>Rewriting method set
Rewriting method set
2022-07-29 01:13:00 【:D...】
Catalog
One 、 View set overrides create
1 Judge the front-end information Avoid repeated addition
(1) Deserialize add data
Use when there is a large amount of data to be added
# Avoid adding problems repeatedly
def create(self, request, *args, **kwargs):
c_name = request.data.get('name')
c_coupon_type = request.data.get('coupon_type')
num = Coupon.objects.filter(name=c_name, coupon_type_id=c_coupon_type).count()
if num > 0:
return Response({
'msg': ' This coupon has been added '}, status=400)
else:
# Deserialize add data
ser = self.get_serializer(data=request.data)
ser.is_valid()
ser.save()
return Response({
'msg': ' Add success '}, status=201)
(2) Normal add data
Suitable for small amount of data
# Duplicate additions are not allowed
def create(self, request, *args, **kwargs, ):
name = request.data.get('value')
spec = request.data.get('spec')
# print('$$$$$$$ Get objects ->', name, '$$$$$$$ type ->', type(name),)
num = SpecOption.objects.filter(value=name).count()
if num > 0:
return Response({
'msg': " Add repeatedly ", 'status': 400})
else:
SpecOption.objects.create(value=name, spec_id=spec)
return Response({
'msg': " Add success ", 'status': 201})
2 Serializer verification increases , Judge whether the information contains xx
#SPU An increase in increases , Pay attention to judgment SPU Does the name contain Xiaomi ,
def validate_name(self, name):
if ' millet ' in name:
return name
else:
raise ValidationError('SPU The name does not include Xiaomi , Add failure ')
Two 、destroy
1 Only delete... Is allowed contain xx Of SPU
# SPU The deletion of , Only delete names that contain Millet TV Of SPU
def destroy(self, request, *args, **kwargs):
spu = self.get_object()
print('xxxxxxxxxx>>>>>>>', spu,'xxxxxxxxxx>>>>>>>', type(spu), spu.name)
name = spu.name
if ' Millet TV ' in name:
SPU.objects.get(name=name).delete()
return Response({
'msg': ' Delete successful ', 'status': 201})
return Response({
'msg': ' The name does not include Xiaomi TV , Delete failed ', 'status': 400})
2 Only delete... Is allowed The foreign key field contains xx Of
# Only delete... Is allowed spu The name of Xiaomi has the specification of Xiaomi ;
def destroy(self, request, *args, **kwargs):
spec = self.get_object()
print('xxxxxxxxxx>>>>>>>', spec,'xxxxxxxxxx>>>>>>>', type(spec), spec.spu, spec.name, spec.id)
if ' millet ' in spec.spu.name:
idq = spec.id
SpuSpecification.objects.get(id=idq).delete()
return Response({
'msg': ' Delete successful ', 'status': 201})
return Response({
'msg': ' The name does not include Xiaomi TV , Delete failed ', 'status': 400})
3、 ... and 、update
1 Modify only xx Fields containing numeric
# Only specification values containing values can be modified ! Such as " aluminium alloy " It's not allowed to modify , and "181g" Allow modification .
def update(self, request, *args, **kwargs):
option = self.get_object()
value = option.value
n_value = request.data.get('value')
n_spec = request.data.get('spec')
num_in = re.search(r'\d', value)
if num_in:
option.value = n_value
option.spec_id = n_spec
option.save()
return Response({
'msg': " Include values , Modification successful "}, status=201)
else:
return Response({
'msg': " Does not contain values , Modification failed "}, status=400)
2 When the front end submits the modification , Deserialize the inbound fields plus other information
# SPU modify When the front end submits the modification , When deserializing warehousing ,SPU Add your own name after your name ,
# such as millet 10, Deserialization warehousing is millet 10_jack modify .
def update(self, request, *args, **kwargs):
spu = self.get_object()
# print('xxxxxxx>>>>>>', spu, type(spu), '<<<<<', spu.desc_detail)
name = request.data.get('name')
spu.name = name+'_luoting modify '
spu.brand_id = request.data.get('brand')
spu.category1_id = request.data.get('category1')
spu.category2_id = request.data.get('category2')
spu.category3_id = request.data.get('category3')
spu.desc_detail = request.data.get('desc_detail')
spu.desc_pack = request.data.get('desc_pack')
spu.desc_service = request.data.get('desc_service')
spu.brand_name = request.data.get('brand_name')
spu.save()
return Response({
'status': 200, 'message': 'SPU Modification successful '})
3 Modify the simple process
# rewrite update
def update(self, request, *args, **kwargs):
# 1 Take over front-end data
status = request.data.get('status')
# 2 Get the object to update
order = self.get_object()
# 3 Update status
order.status = status
order.save()
return Response({
'code':200, 'msg': ' Update status succeeded '})
Four list
1 Show subclasses
# Get subcategories 2,3 channel/categories/
class SubsCate(ListAPIView):
queryset = Cate.objects.all()
serializer_class = Cate_Serializer
lookup_field = 'pk'
def list(self, request, *args, **kwargs):
cate_subs = self.get_object().subs.all() # object .subs.all() The reverse query method defined by the model class
ser = Cate_Serializer(cate_subs, many=True)
return Response(ser.data)
5、 ... and retrieve
1 Return the requested json data
# rewrite retrieve retrieval Return the requested json data
def retrieve(self, request, *args, **kwargs):
order = self.get_object()
order_ser = OrderInfo_Serializer(order)
order_goods = order.orderGoods.all()
order_goods_ser = OrderGood_Serializer(order_goods, many=True)
temp = []
for i in order_goods_ser.data:
i['sku'] = Good_Serializer(Good.objects.filter(id=i.get('sku')).first()).data
# Save to a temporary list
temp.append(i)
order_dict = order_ser.data
order_dict['skus'] = temp
return Response(order_dict)
6、 ... and Involving users Add modification Need encryption
The article links
http://t.csdn.cn/JdqI5
边栏推荐
- 🧐 table1 | 一秒搞定你的三线表
- Y80. Chapter 4 Prometheus big factory monitoring system and practice -- Kube state metrics component introduction and monitoring extension (XI)
- 大页内存原理及使用设置
- MySQL stored procedure realizes the creation of a table (copy the structure of the original table and create a new table)
- PLATO上线LAAS协议Elephant Swap,用户可借此获得溢价收益
- RHCE命令练习(一)
- B-tree~
- Django使用MySQL数据库已经存在的数据表方法
- dart数组,Map,类型判断,条件判断运算符,类型转换
- 递归与分治
猜你喜欢

Day2:三种语言暴刷牛客130题

Seven marketing strategies of NFT project

How to deal with the time, scope and cost constraints in the project?

What are the methods to track the real-time market of London Silver?

Tupu software appeared at the 2022 Fuzhou digital Expo to jointly create a new digital era
![[AD learning] the course of PCB drawing in this marine vehicle competition](/img/37/211a0557848f6922fda7a69a114923.png)
[AD learning] the course of PCB drawing in this marine vehicle competition

QT static compiler (MinGW compilation)

电子招标初学者指南

用CDO进行nc数据的不规则裁剪

表达式求值
随机推荐
Irregular clipping of NC data with CDO
regular expression
指令重排、happens-before、as-if-serial
Cookies and sessions
【mysql】字符串转int
(update 20211130) about the download and installation of Jupiter notebook and its own configuration and theme
This article enables you to understand the underlying principle of MySQL- Internal structure, index, lock, cluster
(完美解决)为什么在train/val/test数据集上用train模式效果都很好,但是在eval模式下全部很差
Digital twin rail transit: "intelligent" monitoring to clear the pain points of urban operation
In the second round, 1000 okaleido tiger were sold out in one hour after logging in to binance NFT again
LeTax记录\documentclass{},authoryear属性使用
一元函数积分学之1__不定积分
Wechat campus bathroom reservation applet graduation design finished product (8) graduation design thesis template
Y80. Chapter 4 Prometheus big factory monitoring system and practice -- Kube state metrics component introduction and monitoring extension (XI)
时间复杂度、空间复杂度的学习总结
(perfect solution) why is the effect of using train mode on the train/val/test dataset good, but it is all very poor in Eval mode
新一代超安全蜂窝电池,思皓爱跑上市,13.99万起售
教你一文解决 js 数字精度丢失问题
Django使用MySQL数据库已经存在的数据表方法
“index [hotel/jXLK5MTYTU-jO9WzJNob4w] already exists“