Skip to content

DRF Sample Step

冒菜略寡味 edited this page May 9, 2018 · 5 revisions

DRF项目结构搭建

DRF即:Django REST framework

DRF开发主要步骤大体如下:

创建模型Model -> 创建序列化器Serializer -> 创建视图View -> 组建路由Router

项目目录结构如下:

.
├── LICENSE
├── Pipfile # 相关依赖管理文件
├── Pipfile.lock
├── README.md
├── accountbook # 项目相关
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── api  # API 入口
├── apps # 应用 入口
│   ├── bills # 账目相关
│   │   ├── __init__.py
│   │   ├── admin.py
│   │   ├── apps.py
│   │   ├── migrations
│   │   │   ├── 0001_initial.py
│   │   │   └── __init__.py
│   │   ├── models.py
│   │   ├── serializers.py
│   │   ├── tests.py
│   │   └── views.py
│   ├── categorys # 类别相关
│   │   ├── __init__.py
│   │   ├── admin.py
│   │   ├── apps.py
│   │   ├── migrations
│   │   │   ├── 0001_initial.py
│   │   │   └── __init__.py
│   │   ├── models.py
│   │   ├── serializers.py
│   │   ├── tests.py
│   │   └── views.py
│   ├── summaries # 概要统计相关
|   |   └── ...
│   ├── users # 用户相关
|   |   └── ...
│   └── utils # 工具相关
|       └── ...
└── manage.py

1. 安装 REST 框架包

$ pipenv install djangorestframework==3.8.2

2. 创建应用

$ mkdir -p apps/utils
$ mkdir -p apps/users
$ mkdir -p apps/bills
$ mkdir -p apps/categorys
$ mkdir -p apps/summaries
$ python manage.py startapp utils apps/utils # 工具相关
$ python manage.py startapp users apps/users # 用户相关
$ python manage.py startapp bills apps/bills # 账目相关
$ python manage.py startapp categorys apps/categorys # 分类相关
$ python manage.py startapp summaries apps/summaries # 统计相关

3. 在配置中添加新增的应用

accountbook/settings.py文件中添加新增的应用

INSTALLED_APPS = [
    ...
    'rest_framework',
    'apps.utils',
    'apps.users',
    'apps.bills',
    'apps.categorys',
    'apps.summaries',
]

4. 创建账目bills及分类categorys数据模型

  • apps/categorys/models.py:
from django.db import models
from django.contrib.auth.models import User

class Categorys(models.Model):
    """
    账目明细分类表
    """
    OUTGO = '0'     # 账目类型.支出
    INCOME = '1'    # 账目类型.收入
    TYPE_CHOICE = (
        (OUTGO, 'OUTGO'),
        (INCOME, 'INCOME'),
    )

    is_default = models.BooleanField('是否默认分类', default=True) # True:默认存在分类 False:用户自定义分类
    user = models.ForeignKey(User, verbose_name='自定义分类所属用户', blank=True, null=True, on_delete=models.CASCADE)
    bill_type = models.CharField('账目类型', max_length=1, choices=TYPE_CHOICE, default=OUTGO)
    name = models.CharField('分类名称', max_length=20, unique=True) 
    parent = models.ForeignKey('self', verbose_name='父级分类', blank=True, null=True, on_delete=models.CASCADE)
    modify_time = models.DateTimeField('修改时间', auto_now=True)
    create_time = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        db_table = "categorys"
  • apps/bills/models.py:
from django.db import models
from django.contrib.auth.models import User
from apps.categorys.models import Categorys

class Bills(models.Model):
    """
    账目信息表
    """
    OUTGO = '0'     # 账目类型.支出
    INCOME = '1'    # 账目类型.收入
    TYPE_CHOICE = (
        (OUTGO, 'OUTGO'),
        (INCOME, 'INCOME'),
    )

    user = models.ForeignKey(User, verbose_name='账目所属用户', blank=True, null=True, on_delete=models.CASCADE)
    bill_type = models.CharField('账目类型', max_length=1, choices=TYPE_CHOICE, default=OUTGO)
    category = models.ForeignKey(Categorys, verbose_name='明细分类', blank=True, null=True, on_delete=models.CASCADE)
    amount = models.DecimalField('账目金额', max_digits=16, decimal_places=2, default=0)
    record_date = models.DateField('记录时间', auto_now=True)
    remarks = models.CharField('备注信息', max_length=140) # 至多140字
    modify_time = models.DateTimeField('修改时间', auto_now=True)
    create_time = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        db_table = "bills"

5. 迁移 Magrate

# 生成迁移文件
$ python manage.py makemigrations

# 查看应用中的迁移SQL
$ python manage.py sqlmigrate bills 0001
$ python manage.py sqlmigrate categorys 0001

# 执行迁移
$ python manage.py migrate

6. 序列化 Serializers

  • apps/categorys/serializers.py:
from rest_framework import serializers
from apps.categorys.models import Categorys

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Categorys
        fields = ('id', 'user_id', 'parent_id', 'is_default', 'bill_type', 'name')
  • apps/categorys/serializers.py:
from rest_framework import serializers
from apps.bills.models import Bills

class BillSerializer(serializers.ModelSerializer):
    class Meta:
        model = Bills
        fields = ('user_id', 'category_id', 'bill_type', 'amount', 'remarks', 'record_date')

7. DRF视图集(ViewSet)实现 Views

  • apps/bills/views.py:
from apps.bills.models import Bills
from apps.bills.serializers import BillSerializer
from rest_framework import viewsets

class BillsViewSet(viewsets.ModelViewSet):
    queryset = Bills.objects.all()
    serializer_class = BillSerializer
  • apps/categorys/views.py:
from apps.categorys.models import Categorys
from apps.categorys.serializers import CategorySerializer
from rest_framework import viewsets

class CategorysViewSet(viewsets.ModelViewSet):
    queryset = Categorys.objects.all()
    serializer_class = CategorySerializer

8. 建立DRF路由 Routers

accountbook/urls.py:

from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from apps.bills.views import BillsViewSet
from apps.categorys.views import CategorysViewSet

router = routers.DefaultRouter()
router.register(r'bills', BillsViewSet)
router.register(r'categorys', CategorysViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(router.urls))
]

最后默认访问:http://127.0.0.1:8000/api/ 查看API页面

昨日擔當 昨日敢想

昨日轉眼 就跌撞

夏時夢長 秋時晝短

清冽途上 不遠望

Clone this wiki locally