1. 创建django项目
需要安装2个依赖包:
pip install django-filter
pip install djangorestframework
创建项目:
django-admin startproject restful
继续创建任意app,如main
cd restful
python manage.py startapp main
项目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. 创建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. 视图函数
在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类用来进行字段筛选,假设这里需要根据name,price来筛选product
ProductViewSet类继承viewsets.ModelViewSet,这样可以在模型基础批量创建模型的增删改查功能。
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里注册ProductViewSet,这样可以直接生成增删改查的url。
6. 测试
终端运行:
python manage.py runserver 0.0.0.0:8001
- 查看product list
http://127.0.0.1:8001/product/
- 创建product
postman: http://127.0.0.1:8001/product/
调用post方法,data={"name":"runrun", "price":12}这样就创建了一个product
- 查看product detail
http://127.0.0.1:8001/product/2/
- 更新product
postman: http://127.0.0.1:8001/product/2/
调用put方法,data={"name":"put", "price":1223}
- 删除product
postman: http://127.0.0.1:8001/product/2/
调用delete方法,删除id=2的product
- 查询product
http://127.0.0.1:8001/product/?name=test
http://127.0.0.1:8001/product/?price=12