官网:https://www.django-rest-framework.org/
中文文档:https://q1mi.github.io/Django-REST-framework-documentation/
安装:
pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support
配置:
settings.py: INSTALLED_APPS = [ ... 'rest_framework',]
urls.py: url(r'^api-auth/', include('rest_framework.urls')) #django2 中 re_path(r'^api-auth/', include('rest_framework.urls'))
简单实验:
models.py
from django.db import models
# Create your models here.
class BaseModel(models.Model):
created_time = models.DateTimeField(auto_now_add=True,verbose_name='创建时间')
updated_time = models.DateTimeField(auto_now=True,verbose_name="修改时间")
class Meta:
abstract = True
class Brand(BaseModel):
name = models.CharField(max_length=20,verbose_name='品牌')
class Goods(BaseModel):
name = models.CharField(max_length=20,verbose_name='商品名字',null=True)
price = models.DecimalField(max_digits=7,decimal_places=2,default=0.00,verbose_name='价格')
brand = models.ForeignKey(Brand,on_delete=models.CASCADE)
class Meta:
db_table = 'goods_goods_details'
def __str__(self):
return self.name
serializers.py中:
from rest_framework import serializers
from .models import Goods,Brand
class BrandSerializer(serializers.ModelSerializer):
class Meta:
model = Brand
fields = '__all__'
class GoodsSerializer(serializers.ModelSerializer):
#外键也可以序列化
#brand = BrandSerializer()
class Meta:
model =Goods
fields = '__all__'
def create(self, validated_data):
return Goods.objects.create(**validated_data)
urls.py中
from django.urls import re_path
from goods.views import GoodsView
urlpatterns = [
re_path(r'^/goods$',GoodsView.as_view(),name='goods'),
]
views.py中
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from rest_framework import status
from rest_framework.pagination import PageNumberPagination
from rest_framework.parsers import JSONParser
from goods.models import Goods
# Create your views here.
from django.views import View
from django.core import serializers
from rest_framework.views import APIView
from .serializers import GoodsSerializer
from rest_framework.response import Response
from rest_framework import generics,viewsets,mixins
class GoodsPagination(PageNumberPagination):
page_size = 1
page_size_query_param = 'page_size'
page_query_param = 'p'
max_page_size = 100
class GoodsViewSet(viewsets.GenericViewSet,mixins.ListModelMixin):
queryset = Goods.objects.all()
serializer_class = GoodsSerializer
pagination_class = GoodsPagination
def dispatch(self, request, *args, **kwargs):
print(request.method)
return super().dispatch(request, *args, **kwargs)
#
#
# def post(self, request, format=None):
# serializer = GoodsSerializer(data=request.data)
# if serializer.is_valid():
# serializer.save()
# print(serializer.data)
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)