Django:数据查询
1.路由配置: urls.py
1 from rest_framework.routers import DefaultRouter 2 from goods.views import GoodsListViewSet 3 from django.urls import path 4 5 # 注册视图 6 r = DefaultRouter() 7 r.register('goods', GoodsListViewSet, base_name='goods') 8 9 urlpatterns = [ 10 path('api/v1/', includ(r.urls)) 11 ]
2.建立数据库模型: app/models.py
1 from django.db import models 2 3 class Goods(models.Model): 4 # verbose_name参数用于在管理后台显示 5 # help_text参数用于生成api文档时显示 6 name = models.CharField(max_length=300, verbose_name='商品名称', help_text='商品名称') 7 shop_price = models.IntegerField(default=0, verbose_name='本店价格', help_text='本店价格') 8 goods_num = models.IntegerField(default=0, verbose_name='库存数', help_text='库存数') 9 goods_desc = RichTextUploadingField(verbose_name='详情描述', help_text='详情描述') 10 add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加时间') 11 12 class Meta: 13 # 自定义表名称 14 db_table='goods' 15 # 表字段排序 16 ordering = ('add_time',) 17
3.数据库更新
检查更新:python manage.py makemigrations
数据库同步: python manage.py migrate
4.创建序列化器: app/serializers.py
1 from rest_framework import serializers 2 from .models import Goods 3 4 class GoodsSerializer(serializers.ModelSerializer): 5 class Meta: 6 # 使用写好的数据库模型 7 model = Goods 8 # 过滤要返回的字段 9 fields = ('id', 'name', 'shop_price', 'goods_num', 'goods_desc')
5.创建视图类:app/views.py
1 from rest_framework import mixins, viewsets 2 from .serializers import GoodsSerializer 3 from .models import Goods 4 5 class GoodsListViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): 6 # 获取所有的商品信息 7 queryset = Goods.objects.all() 8 serializer_class = GoodsSerializer
6.在数据表中插入测试数据
7.启动服务,查看结果