1. 創(chuàng)建django項(xiàng)目
需要安裝2個(gè)依賴包:
pip install django-filter
pip install djangorestframework
創(chuàng)建項(xiàng)目:
django-admin startproject restful
繼續(xù)創(chuàng)建任意app篇恒,如main
cd restful
python manage.py startapp main
項(xiàng)目setting.py文件下爽锥,加入自己的app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'django_filters',
'main',
]
2. 創(chuàng)建models
以product為例属拾,
class Product(models.Model):
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=100, default='')
describe = models.CharField(max_length=500, default='')
price = models.FloatField()
isDelete = models.BooleanField(default=False)
class Meta:
ordering = ('created',)
3. 序列化
在app文件夾下新建serializers.py文件
from rest_framework import serializers
from main.models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
4. 視圖函數(shù)
在app文件夾下的view.py中:
from rest_framework import viewsets
from main.serializers import ProductSerializer
from main.models import Product
from django_filters import rest_framework as filters
class ProductFilter(filters.FilterSet):
class Meta:
model = Product
fields = ['name', 'price', ]
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_class = ProductFilter
這里的ProductFilter類用來(lái)進(jìn)行字段篩選毅戈,假設(shè)這里需要根據(jù)name,price來(lái)篩選product
ProductViewSet類繼承viewsets.ModelViewSet攘须,這樣可以在模型基礎(chǔ)批量創(chuàng)建模型的增刪改查功能戈擒。
5. 路由配置
在main下的url.py文件下
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from main import views
router = DefaultRouter()
router.register(r'product', views.ProductViewSet)
# api url 配置
urlpatterns = [
url(r'^', include(router.urls)),
]
這里直接在router里注冊(cè)ProductViewSet苞慢,這樣可以直接生成增刪改查的url申鱼。
6. 測(cè)試
終端運(yùn)行:
python manage.py runserver 0.0.0.0:8001
- 查看product list
- 創(chuàng)建product
postman: http://127.0.0.1:8001/product/
調(diào)用post方法,data={"name":"runrun", "price":12}這樣就創(chuàng)建了一個(gè)product
- 查看product detail
- 更新product
postman: http://127.0.0.1:8001/product/2/
調(diào)用put方法,data={"name":"put", "price":1223}
- 刪除product
postman: http://127.0.0.1:8001/product/2/
調(diào)用delete方法,刪除id=2的product
- 查詢product