Django restful-framework初步学习

时间:2022-12-06 16:17:05

urls.py

from django.conf.urls import include, url
from django.contrib import admin
from rest_framework import routers # 导入api路由
from app01 import api router = routers.DefaultRouter() # 获取api路由对象
router.register(r'users', api.UserViewSet) # 注册路由到指定的ViewSet类
router.register(r'blogs', api.BlogViewSet) # 注册路由到指定的ViewSet类 urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include(router.urls)), # 设置api路由转发
]

api.py 序列化处理文件

from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
from app01 import models
from rest_framework import response class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url','username','email','is_staff') class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer # 指定处理序列化的类 class BlogSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Blog
depth = 1
fields = ('url','title','content',) class BlogViewSet(viewsets.ModelViewSet):
queryset = models.Blog.objects.all()
serializer_class = BlogSerializer

models.py

from django.db import models

# Create your models here.

class Blog(models.Model):

    title = models.CharField(max_length = 50 )
content = models.TextField()

Django restful-framework初步学习

Django restful-framework初步学习

Django restful-framework初步学习