欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

初步使用DRF(rest_framework)

程序员文章站 2022-05-23 08:38:40
...

使DRF(RestFramework)初步使用DRF-(RestFramework)

****:B站、网易云课堂、腾讯课堂
代码地址:Gitee、Github
存储地址:
Google云

百度云:https://pan.baidu.com/s/180FqTm7pljbqLkEuLa_4LA
提取码:cd5b


一 前期须知

  • 安装
pip install djangorestframework
  • settings注册
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'apps.drf_demo',
    'rest_framework',
]

二 主要工程目录

初步使用DRF(rest_framework)


  • test002文件下重要文件:

1.urls.py

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('drf_demo/',include('apps.drf_demo.urls'))
]

2.settings.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'apps.drf_demo',
    'rest_framework',
]

DATABASES = {
 'default': {
	# 数据库引擎(是mysql还是oracle等)
	'ENGINE': 'django.db.backends.mysql',
	# 数据库的名字
	'NAME': 'DjangoDB',
	# 连接mysql数据库的用户名
	'USER': 'root',
	# 连接mysql数据库的密码
	'PASSWORD': '123456',
	# mysql数据库的主机地址
	'HOST': '127.0.0.1',
	# mysql数据库的端口号
	'PORT': '3306',
  }
}


  • apps.drf_demo文件下重要文件:

1.models.py

from django.db import models

# Create your models here.
class Person(models.Model):
    name = models.CharField(max_length=100,null=False)
    address = models.CharField(max_length=100,null=False)

2.serializers.py

from rest_framework import serializers
from .models import Person

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields= "__all__"
        # exclude = ['','',]

3.urls.py

from rest_framework.routers import DefaultRouter
from .views import PersonViewset

router = DefaultRouter()
router.register('person',PersonViewset,basename='person')


app_name = 'drf_demo'
urlpatterns = []+router.urls

4.views.py

from rest_framework import viewsets
from .models import Person
from .serializers import PersonSerializer

# 这个视图函数已经包含了增删改查操作
class PersonViewset(viewsets.ModelViewSet):
    queryset = Person.objects.all()
    serializer_class = PersonSerializer


六 推荐****和资料等