django rest_framework的简单使用
程序员文章站
2022-05-23 08:35:11
...
- Django版本:django 2.0
- python版本:python 3.6
首先新建一个Django项目,例如我创建的项目名称是:djangoRestful
接着新建一个app,我新建的app叫:restful
修改settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 安装下面两个app,一个是我自己创建的,一个是使用Django的api框架
'restful',
'rest_framework',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库的类别
'NAME': 'test', # 数据库的名字
'HOST': '127.0.0.1', # 数据库的ip
'USER': 'root', # 用户名
'PASSWORD': '5201314' # 密码
}
}
作者使用的数据库是mysql,我自己新建了一个空的数据库:test
修改restful包下的models.py:
from django.db import models
# Create your models here.
class Book(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5, decimal_places=2)
publish_date = models.DateField(null=True)
kind = models.IntegerField(choices=((0, '文学类'), (1, '情感类')), default=1, null=True)
publish = models.ForeignKey(to='Publish', to_field='nid', on_delete=models.CASCADE, null=True)
authors = models.ManyToManyField(to='Author')
def __str__(self):
return self.name
class Author(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
age = models.IntegerField()
class Publish(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
city = models.CharField(max_length=32)
email = models.EmailField()
def __str__(self):
return self.name
在项目所在目录路径下,在命令提示符窗口执行下面两个语句,目的是在数据库创建相应的表,有点Django基础的都懂:
python manage.py makemigrations
python manage.py migrate
在restful包下新建一个serializers.py:
from rest_framework import serializers
class BookSerializer(serializers.Serializer):
name = serializers.CharField()
price = serializers.CharField()
这个文件是用来序列化对象的。
修改restful包下的view.py:
from rest_framework.response import Response
# 需要导入下面3个模块
from rest_framework.views import APIView
from . import models
from .serializers import BookSerializer
class Books(APIView):
def get(self, request):
response = {'code': 100, 'msg': '查询成功'}
books = models.Book.objects.all()
# 如果序列化是多个,就要传入many=true,序列化一条可以不写
bookser = BookSerializer(books, many=True)
response['data'] = bookser.data
return Response(response)
在restful包下新建urls.py:
from django.urls import path
from . import views
app_name = 'api'
urlpatterns = [
path('api/', views.Books.as_view(), name='api'),
]
修改djangoRestful目录下的urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('restful.urls')),
]
到目前为止,项目已经编写完毕,下面开始测试:
我们先在数据库中加入一些数据,方便一会测试
然后启动项目:
python manage.py runserver 127.0.0.1:8000
在浏览器中输入网址:http://127.0.0.1:8000/api/
结果如下: