django rest framework 数据的查找、过滤、排序的示例

对于管理系统,常常需要展示列表数据,我们对于列表内的数据常常需要查找、过滤、排序等操作,其中查找等操作大部分是在后台进行的。django rest framework可以轻松的实现数据的查找、过滤等操作。接下来我们将以实际的例子进行介绍。

示例代码github地址: https://github.com/jinjidejuren/drf_learn

例如cmdb系统,作为资产管理系统常常需要对数据进行过滤或查找,获取期望的信息。

实现model

1.在这个示例项目中,需要实现对物理服务器的条件过滤,物理服务器的model列表如下(apps/assets/models.py文件):

class Server(models.Model):
  """
  物理服务器
  """
  status_choice = (
    ('online', '上线'),
    ('offline', '下线'),
    ('normal', '正常'),
    ('abnormal', '异常')
  )

  server_name = models.CharField(verbose_name=u'服务器名称', max_length=128, blank=False, null=False)
  server_num = models.CharField(verbose_name=u'服务器编号', max_length=128, blank=True, null=True)
  brand = models.CharField(verbose_name=u'品牌', max_length=64, blank=True, null=True)
  model = models.CharField(verbose_name=u'型号', max_length=64, blank=True, null=True)
  cpus = models.IntegerField(verbose_name=u'cpu核数', default=0)
  ram = models.IntegerField(verbose_name=u'内存大小', default=0)
  disk = models.IntegerField(verbose_name=u'磁盘大小', default=0)
  product_date = models.DateTimeField(verbose_name=u'生产日期', auto_now_add=True)
  status = models.CharField(verbose_name=u'状态', max_length=16, choices=status_choice)

  created_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
  modified_time = models.DateTimeField(verbose_name=u'修改时间', auto_now_add=True)

  class Meta:
    verbose_name = u'服务器'
    verbose_name_plural = verbose_name

  def __str__(self):
    return self.server_name

实现serializer

接下来需要实现server这个model的序列化类,在apps/assets/serializers.py中编写:

class ServiceSerializer(serializers.ModelSerializer):
  """
  服务器序列化
  """

  class Meta:
    model = Server
    fields = ('id', 'server_name', 'server_num', 'brand', 'model', 'cpus',
         'ram', 'disk', 'product_date', 'status', 'created_time',
         'modified_time')

对于fields来说,可以使用 _ all _ 来代表所有的字段,除了model中定义的field外,序列化还可以指定其他的信息,比如嵌套信息或者自定义的信息。具体可以取决于业务逻辑。

实现modelviewset

对于modelviewset,我们可以围绕它对用户请求做相应的处理。常见的是对model进行增加、删除、查找、修改等。在这部分我们需要实现ServerViewSet:

class ServerViewSet(viewsets.ModelViewSet):
  """
  物理服务器视图
  """
  queryset = Server.objects.all().order_by('-created_time')
  serializer_class = ServerSerializer
  pagination_class = MyFormatResultsSetPagination

queryset指定返回列表的形式,所有的信息都返回,并且按照创建时间逆序排列,这样可以把最新的信息先返回,比较符合用户的操作习惯。

serializer_class定义了返回的序列化格式为ServerSerializer所指定的fields内容

pagination_class 指定了分页的类型,这个MyFormatResultsSetPagination是我们的自定义类型

实现router

如果用户想要访问server的信息,需要指定server的路由,这个和之前介绍的类似。需要的嗯一个一个router对象,并且将server的路由注册进去。

from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'servers', views.ServerViewSet, base_name='servers')

urlpatterns = [
  url(r'^', include(router.urls))
]

对于servers的访问都由ServerViewSet进行处理。

尝试访问

http://127.0.0.1:8060/assets/v1/servers/ ,信息如下:

注:我们需要添加示例信息,作为后续的各种测试使用。

按照条件获取

在日常操作中,我们需要获取指定条件的数据,例如对于物理服务器,我们需要指定品牌、指定cpu核数、指定内存大小等。有时候我们需要按照cpu核数进行排序。这些都需要我们对ServerViewSet进行更多的拓展。

如果进行条件过滤,需要首先安装django-filter模块:

pip install django-filter

在配置文件settings/base.py中添加应用django_filters:

INSTALLED_APPS = [
  # 'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  'rest_framework',
  'django_filters',
  'apps.assets',
  'apps.rbac'
]

在apps/assets/views.py顶部包含如下包:

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from django_filters import rest_framework

ServerViewSet可以添加相应的过滤条件:

class ServerViewSet(viewsets.ModelViewSet):
  """
  物理服务器视图
  """
  queryset = Server.objects.all()
  serializer_class = ServerSerializer
  pagination_class = MyFormatResultsSetPagination
  filter_backends = (rest_framework.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter, )
  filter_class = ServerFilter
  search_fields = ('server_name', '=brand', 'status', )
  ordering_fields = ('cpus', 'ram', 'disk', 'product_date', )
  ordering = ('-created_time', )

这里的filter_backends指定了过滤的类型,此处设定了DjangoFilterBackend(过滤)、SearchFilter(搜索)和OrderingFIlter(排序)。

1.过滤

过滤设定了过滤的配置类为ServerFilter,关于ServerFilter在apps/assets/filters.py文件中进行了定义:

import django_filters

from .models import *

class ServerFilter(django_filters.rest_framework.FilterSet):
  """
  物理服务器过滤器
  """

  server_name = django_filters.CharFilter(name='server_name', lookup_expr='icontains')
  brand = django_filters.CharFilter(name='brand', lookup_expr='icontains')
  cpus = django_filters.NumberFilter(name='cpus')
  ram = django_filters.NumberFilter(name='ram')
  disk = django_filters.NumberFilter(name='disk')

  class Meta:
    model = Server
    fields = ['server_name', 'brand', 'cpus', 'ram', 'disk', ]

也就是说可以通过'server_name', ‘brand', ‘cpus', ‘ram', ‘disk'对物理服务器的信息进行过滤,得到相应的序列化列表。

例如获取cpu为24核的物理服务器:

得到物理服务器列表中cpu都为24:

GET /assets/v1/servers/?server_name=&brand=&cpus=24&ram=&disk=
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
  "results": [
    {
      "id": 9,
      "server_name": "data-server2",
      "server_num": "server-01-shanghai",
      "brand": "hp",
      "model": "HPE Apollo 4200 Gen9",
      "cpus": 24,
      "ram": 64,
      "disk": 2500,
      "product_date": "2018-06-23T13:51:09.641473Z",
      "status": "online",
      "created_time": "2018-06-23T13:51:09.642583Z",
      "modified_time": "2018-06-23T13:51:09.642764Z"
    },
    {
      "id": 8,
      "server_name": "data-server2",
      "server_num": "server-01-shanghai",
      "brand": "hp",
      "model": "HPE Apollo 4200 Gen9",
      "cpus": 24,
      "ram": 64,
      "disk": 5000,
      "product_date": "2018-06-23T13:51:02.466031Z",
      "status": "online",
      "created_time": "2018-06-23T13:51:02.467274Z",
      "modified_time": "2018-06-23T13:51:02.467471Z"
    },
    {
      "id": 7,
      "server_name": "data-server1",
      "server_num": "server-01-shanghai",
      "brand": "hp",
      "model": "HPE Apollo 4200 Gen9",
      "cpus": 24,
      "ram": 64,
      "disk": 5000,
      "product_date": "2018-06-23T13:50:55.622403Z",
      "status": "offline",
      "created_time": "2018-06-23T13:50:55.623315Z",
      "modified_time": "2018-06-23T13:50:55.623431Z"
    },
    {
      "id": 6,
      "server_name": "data-server",
      "server_num": "server-01-shanghai",
      "brand": "hp",
      "model": "HPE Apollo 4200 Gen9",
      "cpus": 24,
      "ram": 64,
      "disk": 5000,
      "product_date": "2018-06-23T13:50:48.088028Z",
      "status": "online",
      "created_time": "2018-06-23T13:50:48.089433Z",
      "modified_time": "2018-06-23T13:50:48.089703Z"
    },
    {
      "id": 5,
      "server_name": "harbor-server3",
      "server_num": "server-01-beijing",
      "brand": "dell",
      "model": "Rack",
      "cpus": 24,
      "ram": 128,
      "disk": 5000,
      "product_date": "2018-06-23T13:49:27.590015Z",
      "status": "offline",
      "created_time": "2018-06-23T13:49:27.590980Z",
      "modified_time": "2018-06-23T13:49:27.591097Z"
    },
    {
      "id": 4,
      "server_name": "harbor-server3",
      "server_num": "server-01-beijing",
      "brand": "dell",
      "model": "Rack",
      "cpus": 24,
      "ram": 128,
      "disk": 5000,
      "product_date": "2018-06-23T13:49:23.783337Z",
      "status": "abnormal",
      "created_time": "2018-06-23T13:49:23.784243Z",
      "modified_time": "2018-06-23T13:49:23.784500Z"
    },
    {
      "id": 3,
      "server_name": "harbor-server2",
      "server_num": "server-01-beijing",
      "brand": "dell",
      "model": "Rack",
      "cpus": 24,
      "ram": 128,
      "disk": 5000,
      "product_date": "2018-06-23T13:49:16.348672Z",
      "status": "online",
      "created_time": "2018-06-23T13:49:16.349555Z",
      "modified_time": "2018-06-23T13:49:16.349663Z"
    },
    {
      "id": 2,
      "server_name": "harbor-server1",
      "server_num": "server-02-beijing",
      "brand": "dell",
      "model": "Rack",
      "cpus": 24,
      "ram": 128,
      "disk": 5000,
      "product_date": "2018-06-23T13:48:57.853354Z",
      "status": "online",
      "created_time": "2018-06-23T13:48:57.853990Z",
      "modified_time": "2018-06-23T13:48:57.854098Z"
    },
    {
      "id": 1,
      "server_name": "harbor-server",
      "server_num": "server-01-beijing",
      "brand": "dell",
      "model": "Rack",
      "cpus": 24,
      "ram": 128,
      "disk": 5000,
      "product_date": "2018-06-23T13:48:48.777153Z",
      "status": "online",
      "created_time": "2018-06-23T13:48:48.778048Z",
      "modified_time": "2018-06-23T13:48:48.778166Z"
    }
  ],
  "pagination": 9,
  "page_size": 10,
  "page": 1
}

2.搜索

搜索需要指定 search 关键字需要查询的信息,例如搜索名称为‘test'开头的服务器:

http://127.0.0.1:8060/assets/v1/servers/?search=test

获取列表:

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
  "results": [
    {
      "id": 14,
      "server_name": "test-server1",
      "server_num": "server-01-shanghai",
      "brand": "dell",
      "model": "Modular",
      "cpus": 32,
      "ram": 256,
      "disk": 500,
      "product_date": "2018-06-23T13:52:40.583743Z",
      "status": "offline",
      "created_time": "2018-06-23T13:52:40.584409Z",
      "modified_time": "2018-06-23T13:52:40.584512Z"
    },
    {
      "id": 13,
      "server_name": "test-server",
      "server_num": "server-01-shanghai",
      "brand": "dell",
      "model": "Modular",
      "cpus": 32,
      "ram": 256,
      "disk": 2500,
      "product_date": "2018-06-23T13:52:24.760819Z",
      "status": "normal",
      "created_time": "2018-06-23T13:52:24.761475Z",
      "modified_time": "2018-06-23T13:52:24.761578Z"
    }
  ],
  "pagination": 2,
  "page_size": 10,
  "page": 1
}

在search_fields中可以指定多种查找方式:

‘^name' 以name开头

‘=name' 精确匹配

‘@' 全局检索(只有mysql数据源支持)

‘$' 正则匹配

对应的search_fileds示例如下:

search_fields = ('^server_name', '=brand', 'status', )

3.排序

在ordering字段指定了默认排序方式(按照创建时间逆序排序):

ordering = ('-created_time', )

也可以使用如下方式指定:

queryset = Server.objects.all().order_by('-created_time')

如果要自定义排序字段,需要指定 ordering 字段的内容:

例如按照内存大小排列服务器:

http://127.0.0.1:8060/assets/v1/servers/?ordering=ram

获取的信息列表如下:

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
  "results": [
    {
      "id": 6,
      "server_name": "data-server",
      "server_num": "server-01-shanghai",
      "brand": "hp",
      "model": "HPE Apollo 4200 Gen9",
      "cpus": 24,
      "ram": 64,
      "disk": 5000,
      "product_date": "2018-06-23T13:50:48.088028Z",
      "status": "online",
      "created_time": "2018-06-23T13:50:48.089433Z",
      "modified_time": "2018-06-23T13:50:48.089703Z"
    },
    {
      "id": 7,
      "server_name": "data-server1",
      "server_num": "server-01-shanghai",
      "brand": "hp",
      "model": "HPE Apollo 4200 Gen9",
      "cpus": 24,
      "ram": 64,
      "disk": 5000,
      "product_date": "2018-06-23T13:50:55.622403Z",
      "status": "offline",
      "created_time": "2018-06-23T13:50:55.623315Z",
      "modified_time": "2018-06-23T13:50:55.623431Z"
    },
    {
      "id": 8,
      "server_name": "data-server2",
      "server_num": "server-01-shanghai",
      "brand": "hp",
      "model": "HPE Apollo 4200 Gen9",
      "cpus": 24,
      "ram": 64,
      "disk": 5000,
      "product_date": "2018-06-23T13:51:02.466031Z",
      "status": "online",
      "created_time": "2018-06-23T13:51:02.467274Z",
      "modified_time": "2018-06-23T13:51:02.467471Z"
    },
    {
      "id": 9,
      "server_name": "data-server2",
      "server_num": "server-01-shanghai",
      "brand": "hp",
      "model": "HPE Apollo 4200 Gen9",
      "cpus": 24,
      "ram": 64,
      "disk": 2500,
      "product_date": "2018-06-23T13:51:09.641473Z",
      "status": "online",
      "created_time": "2018-06-23T13:51:09.642583Z",
      "modified_time": "2018-06-23T13:51:09.642764Z"
    },
    {
      "id": 1,
      "server_name": "harbor-server",
      "server_num": "server-01-beijing",
      "brand": "dell",
      "model": "Rack",
      "cpus": 24,
      "ram": 128,
      "disk": 5000,
      "product_date": "2018-06-23T13:48:48.777153Z",
      "status": "online",
      "created_time": "2018-06-23T13:48:48.778048Z",
      "modified_time": "2018-06-23T13:48:48.778166Z"
    },
    {
      "id": 2,
      "server_name": "harbor-server1",
      "server_num": "server-02-beijing",
      "brand": "dell",
      "model": "Rack",
      "cpus": 24,
      "ram": 128,
      "disk": 5000,
      "product_date": "2018-06-23T13:48:57.853354Z",
      "status": "online",
      "created_time": "2018-06-23T13:48:57.853990Z",
      "modified_time": "2018-06-23T13:48:57.854098Z"
    },
    {
      "id": 3,
      "server_name": "harbor-server2",
      "server_num": "server-01-beijing",
      "brand": "dell",
      "model": "Rack",
      "cpus": 24,
      "ram": 128,
      "disk": 5000,
      "product_date": "2018-06-23T13:49:16.348672Z",
      "status": "online",
      "created_time": "2018-06-23T13:49:16.349555Z",
      "modified_time": "2018-06-23T13:49:16.349663Z"
    },
    {
      "id": 4,
      "server_name": "harbor-server3",
      "server_num": "server-01-beijing",
      "brand": "dell",
      "model": "Rack",
      "cpus": 24,
      "ram": 128,
      "disk": 5000,
      "product_date": "2018-06-23T13:49:23.783337Z",
      "status": "abnormal",
      "created_time": "2018-06-23T13:49:23.784243Z",
      "modified_time": "2018-06-23T13:49:23.784500Z"
    },
    {
      "id": 5,
      "server_name": "harbor-server3",
      "server_num": "server-01-beijing",
      "brand": "dell",
      "model": "Rack",
      "cpus": 24,
      "ram": 128,
      "disk": 5000,
      "product_date": "2018-06-23T13:49:27.590015Z",
      "status": "offline",
      "created_time": "2018-06-23T13:49:27.590980Z",
      "modified_time": "2018-06-23T13:49:27.591097Z"
    },
    {
      "id": 10,
      "server_name": "data-server2",
      "server_num": "server-01-shanghai",
      "brand": "hp",
      "model": "HPE Apollo 4200 Gen9",
      "cpus": 32,
      "ram": 256,
      "disk": 2500,
      "product_date": "2018-06-23T13:51:30.706187Z",
      "status": "online",
      "created_time": "2018-06-23T13:51:30.707754Z",
      "modified_time": "2018-06-23T13:51:30.707878Z"
    }
  ],
  "pagination": 14,
  "page_size": 10,
  "page": 1
}

上述的排序、过滤等操作可以组合使用,一般为前端的列表搜索查询提供接口支持。

小结

本章小结的内容介绍了django rest framework如何进行model的定义、序列化、增删改查以及搜索、排序等功能,是书写后端接口必须掌握的技巧。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Django基础知识与基本应用入门教程

    本文实例讲述了Django基础知识与基本应用.分享给大家供大家参考,具体如下: MVC模式和MTV模式 MVC model view controller MTV model templates view controller Django的MTV模式本质是各组件之间为了保持松耦合关系,Django的MTV分别代表: Model(模型):负责业务对象与数据库的对象(ORM)        Template(模版):负责如何把页面展示给用户        View(视图):负责业务逻辑,并在适当的

  • 详解Django rest_framework实现RESTful API

    一.什么是REST 面向资源是REST最明显的特征,资源是一种看待服务器的方式,将服务器看作是由很多离散的资源组成.每个资源是服务器上一个可命名的抽象概念.因为资源是一个抽象的概念,所以它不仅仅能代表服务器文件系统中的一个文件.数据库中的一张表等等具体的东西,可以将资源设计的要多抽象有多抽象,只要想象力允许而且客户端应用开发者能够理解. 与面向对象设计类似,资源是以名词为核心来组织的,首先关注的是名词.一个资源可以由一个或多个URI来标识.URI既是资源的名称,也是资源在Web上的地址.对某个资

  • Django rest framework实现分页的示例

    第一种分页PageNumberPagination 基本使用 (1)urls.py urlpatterns = [ re_path('(?P<version>[v1|v2]+)/page1/', Pager1View.as_view(),) #分页1 ] (2)api/utils/serializers/pager.py # api/utils/serializsers/pager.py from rest_framework import serializers from api impor

  • 浅谈Django REST Framework限速

    官方文档 settings.py配置 REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/day' } } AnonRateThrottle:用

  • Django rest framework工具包简单用法示例

    本文实例讲述了Django rest framework工具包简单用法.分享给大家供大家参考,具体如下: Django rest framework 工具包做API非常方便. 下面简单说一下几个功能的实现方法. 实现功能为,匿名用户访问首页一分钟能访问3次,登录用户一分钟访问6次,只有登录用户才能访问order页面. 第一步,注册app INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contri

  • Python+Django在windows下的开发环境配置图解

    1         安装配置开发环境 1.1   准备安装 下载以下软件 Eclipse for C/C++ SUN JDK 1.6 不一定要1.6,1.5的也可以 Python3.1  Python2.6.4  Pythone2.5.2 mod_python-3.3.1.win32-py2.5-Apache2.2 MySQL-python-1.2.2.win32-py2.5 pysqlite-2.5.5.win32-py2.5 python.pydev.feature-1.5.0.125198

  • python Django模板的使用方法(图文)

    模版基本介绍模板是一个文本,用于分离文档的表现形式和内容. 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签). 模板通常用于产生HTML,但是Django的模板也能产生任何基于文本格式的文档.来一个项目说明1.建立MyDjangoSite项目具体不多说,参考前面.2.在MyDjangoSite(包含四个文件的)文件夹目录下新建templates文件夹存放模版.3.在刚建立的模版下建模版文件user_info.html 复制代码 代码如下: <html>    <

  • django rest framework之请求与响应(详解)

    前言:在上一篇文章,已经实现了访问指定URL就返回了指定的数据,这也体现了RESTful API的一个理念,每一个URL代表着一个资源.当然我们还知道RESTful API的另一个特性就是,发送不同的请求动作,会返还不同的响应,这篇文章就讲一下django-rest-framework这个工具在这方面给我们带来的便捷操作. 一.Request对象 平时我们在写Django的视图函数的时候,都会带上一个request参数,这样就能处理平时搭建网站时,浏览器访问网页时发出的常规的HttpReques

  • Django rest framework基本介绍与代码示例

    本文研究的主要是Django rest framework的相关内容,分享了example,具体如下. Django REST框架是构建Web API的强大而灵活的工具包. 您可能希望使用REST框架的一些原因: Web浏览的API是您的开发人员的巨大的可用性胜利. 验证策略包括OAuth1a和OAuth2的包. 支持ORM和非ORM数据源的序列化. 如果不需要功能更强大的功能,可以自定义一切 - 只需使用基于功能的常规视图. 广泛的文档和极好的社区支持. 由Mozilla,Red Hat,He

  • Python实现手写一个类似django的web框架示例

    本文实例讲述了Python实现手写一个类似django的web框架.分享给大家供大家参考,具体如下: 用与django相似结构写一个web框架. 启动文件代码: from wsgiref.simple_server import make_server #导入模块 from views import * import urls def routers(): #这个函数是个元组 URLpattern=urls.URLpattern return URLpattern #这个函数执行后返回这个元组

随机推荐