建立django框架的rest服务

1、增加models.py

from utils.model import SoftModel, BaseModel

class Position(BaseModel):
    """
    职位/岗位
    """
    name = models.CharField('名称', max_length=32, unique=True)
    description = models.CharField('描述', max_length=50, blank=True, null=True)

    class Meta:
        verbose_name = '职位/岗位'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

2、增加serializers.py

from rest_framework import serializers
from .models import Position

class PositionSerializer(serializers.ModelSerializer):
    """
    岗位序列化
    """
    class Meta:
        model = Position
        fields = '__all__'

3、增加views.py

from .serializers import PositionSerializer
from rest_framework.viewsets import ModelViewSet
from .models import Position

class PositionViewSet(ModelViewSet):
    """
    岗位-增删改查
    """
    perms_map = {'get': '*', 'post': 'position_create',
                 'put': 'position_update', 'delete': 'position_delete'}
    queryset = Position.objects.all()
    serializer_class = PositionSerializer
    pagination_class = None
    search_fields = ['name','description']
    ordering_fields = ['pk']
    ordering = ['pk']

4、更新数据库

PS D:\django\aidemo> python manage.py makemigrations
Migrations for 'aivisit':
  aivisit\migrations\0001_initial.py
    - Create model Position

5、数据更新

PS D:\django\aidemo> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, aivisit, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

6、新建urls.py

from .views import PositionViewSet
from rest_framework import routers
from django.urls import path, include

router = routers.DefaultRouter()
router.register('position', PositionViewSet, basename="position")
urlpatterns = [
    path('', include(router.urls)),
]

7、引入urls.py

from django.urls import include, path
urlpatterns = [
    #....
    path('api/aivisit/', include('aivisit.urls'))
]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值