1. 安装:
pip install djangorestframework
2. 添加'rest_framework'
到您的INSTALLED_APPS
设置。
python
settings.py
INSTALLED_APPS = [
...
'rest_framework',
]
3. 定义模型
python
models.py
from django.db import models
class 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.name
def __repr__(self):
return self.__str__()
4. 定义 serializers
python
serializers.py
from rest_framework.serializers import ModelSerializer
from .models import BookModel
class BookModelSerializer(ModelSerializer):
class Meta:
model = BookModel
fields = '__all__'
5. 视图
python
views.py
from rest_framework.viewsets import ModelViewSet
from .models import BookModel
from .serializers import BookModelSerializer
class BookModelViewSet(ModelViewSet):
queryset = BookModel.objects.all()
serializer_class = BookModelSerializer