1. 安装:
pip install djangorestframework
2. 添加'rest_framework'
到您的INSTALLED_APPS
设置。
settings.pyINSTALLED_APPS = [...'rest_framework',
]
3. 定义模型
models.pyfrom django.db import modelsclass BookModel(models.Model):name = models.CharField(max_length=64)# 最长6位 小数点后保留两位price = models.DecimalField(max_digits=6, decimal_places=2)author = models.CharField(max_length=32)publish = models.CharField(max_length=32)# 修改时间update_time = models.DateTimeField(auto_now=True)# 第一次时间first_create_time = models.DateTimeField(auto_now_add=True)class Meta:verbose_name = "图书表"def __str__(self):return self.namedef __repr__(self):return self.__str__()
4. 定义 serializers
serializers.pyfrom rest_framework.serializers import ModelSerializer
from .models import BookModelclass BookModelSerializer(ModelSerializer):class Meta:model = BookModelfields = '__all__'
5. 视图
views.pyfrom rest_framework.viewsets import ModelViewSet
from .models import BookModel
from .serializers import BookModelSerializerclass BookModelViewSet(ModelViewSet):queryset = BookModel.objects.all()serializer_class = BookModelSerializer
6. 访问URL
7. 自动生成路由