rest_framework与django配合使用
rest_framework与django配合使用
一、构建表单,在这里我们先构建五个表单,分别是 author book publish user token 后面将会一一用到,如下:
from django.db import models # Create your models here. class User(models.Model): username = models.CharField(max_length=32) password = models.CharField(max_length=32) type_choice = ((1,"普通用户"),(2,"VIP"),(4,"SVIP")) user_type = models.IntegerField(choices=type_choice, default=1) def __str__(self): return self.username class Token(models.Model): user = models.OneToOneField("User") token = models.CharField(max_length=128) def __str__(self): return self.token class Author(models.Model): name = models.CharField(max_length=16) age = models.CharField(max_length=16) def __str__(self): return self.name class Publish(models.Model): title = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.title class Book(models.Model): title = models.CharField(max_length=64) price = models.IntegerField() authors = models.ForeignKey(to="Author") publish = models.ForeignKey(to="Publish") def __str__(self): return self.title
二、对admin组件进行注册,利用admin来录入数据
from django.contrib import admin from app01.models import * # Register your models here. admin.site.register(Book) admin.site.register(Author) admin.site.register(Publish) admin.site.register(User)
三、rest-framework的用法:
1、首先得写好序列化组件:在app01的根目录下面创建一个serializer.py 用来存放每一个组的序列化组件,组件如下:
from rest_framework import serializers from app01.models import * class PublishModelSerializers(serializers.ModelSerializer): class Meta: model = Publish fields = "__all__" class BookModelSerializers(serializers.ModelSerializer): class Meta: model = Book fields = "__all__" class AuthorModelSerializers(serializers.ModelSerializer): class Meta: model = Author fields = "__all__"
2、写好序列化组件之后就可以操作视图Views.py 了,操作如下:
from rest_framework import viewsets from app01.models import * from app01.serializer import * # Create your views here. class AuthorModelView(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorModelSerializers class BookModelView(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookModelSerializers class PublishModelView(viewsets.ModelViewSet): queryset = Publish.objects.all() serializer_class = PublishModelSerializers
3、写完了视图后就可以开始写最主要的url部分了!
from django.conf.urls import url,include from django.contrib import admin from rest_framework import routers from app01 import views router = routers.DefaultRouter() router.register("author",views.AuthorModelView) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include(router.urls)) ]
4、好了,这里就只需要在 Postman 里面输入url了,大功告成!