1.POST请求免于csrf认证
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
写入被修饰的函数
2.POST请求仅要求此函数要通过csrf认证
from django.views.decorators.csrf import csrf_protect
@csrf_protect
仅限 FBV模式
3.jango序列化
import json
from django.core import serializers
from django.http import JsonResponse
goods = Goods.objects.all()
json_data = serializers.serialize('json', goods)
json_data = json.loads(json_data)
return JsonResponse(json_data, safe=False)
返回序列化后的结果
4.使用序列化实现创建对象
serializers.py
class GoodsSerializer(serializers.Serializer):
name = serializers.CharField(required=True, max_length=100)
click_num = serializers.IntegerField(default=0)
post方法创建新对象 同时也有 update 函数
def create(self, validated_data):
return Goods.objects.create(**validated_data)
views.py
class GoodsListViews(APIView):
实现查看操作
def get(self, request, format=None):
goods = Goods.objects.all()[:10]
goods_serializer = GoodsSerializer(goods, many=True)
return Response(goods_serializer.data)
实现添加操作
def post(self, request, format=None):
serializer = GoodsSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
5.简化查询
class GoodsSerializer(serializers.ModelSerializer):
class Meta:
model = Goods
field = ('name', 'add_time')
要返回的字段
field = '__all__'
全部字段
6.分页显示 (url指向 GoodsListViews.as_view())
views.py
class GoodsPagination(PageNumberPagination):
page_size = 10
page_size_query_param = 'page_size'
page_query_param = "p"
max_page_size = 100
class GoodsListViews(generics.ListAPIView):
queryset = Goods.objects.all()
serializer_class = GoodsSerializer
pagination_class = GoodsPagination
serializers.py
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = GoodsCategory
fields = '__all__'
class GoodsSerializer(serializers.ModelSerializer):
category = CategorySerializer()
class Meta:
model = Goods
field = '__all__'
6.对象逆序排列
class Post(models.Model):
pass
class Meta:
ordering=['-id']
# 根据 id 逆排序