博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django rest_framework配合django_filter使用
阅读量:6262 次
发布时间:2019-06-22

本文共 4781 字,大约阅读时间需要 15 分钟。

代码示例:

1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3  4 from django.db import models 5 from django.utils.encoding import python_2_unicode_compatible 6 from apps.ncmdb.models import NcmdbRouterIpTable 7  8  9 TASK_STATUS_NOT_BEGIN = 010 TASK_STATUS_READY = 111 TASK_STATUS_RUNNING = 212 TASK_STATUS_COMPLETED = 313 TASK_STATUS_CANCEL = 414 TASK_STATUS = (15     (TASK_STATUS_NOT_BEGIN, "未开始"),16     (TASK_STATUS_READY, "准备中"),17     (TASK_STATUS_RUNNING, "进行中"),18     (TASK_STATUS_COMPLETED, "已完成"),19     (TASK_STATUS_CANCEL, "已取消"),20 )21 22 TASK_RESULT_SUCCESS = 123 TASK_RESULT_FAILURE = 224 TASK_RESULT = (25     (TASK_RESULT_SUCCESS, "成功"),26     (TASK_RESULT_FAILURE, "失败"),27 )28 29 30 @python_2_unicode_compatible31 class RouterTable(models.Model):32     subnet = models.CharField(max_length=40, verbose_name="目的网段")33     protocol = models.CharField(max_length=32, verbose_name="路由协议", null=True)34     vrf = models.CharField(max_length=64, verbose_name="vrf名称", null=True)35     interface = models.CharField(max_length=64, verbose_name="接口名称", null=True)36     metric = models.CharField(max_length=16, verbose_name="metric值", null=True)37     nexthop = models.CharField(max_length=40, verbose_name="路由下一跳", null=True)38     preference = models.CharField(max_length=16, verbose_name="路由优先级", null=True)39     device = models.ForeignKey(to=NcmdbRouterIpTable, null=True)40     create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")41 42     def __str__(self):43         return "{}_{}".format(self.__class__.__name__, self.subnet)44 45     class Meta:46         db_table = "rtm_router_table"47 48 49 class RouterTableCollectTask(models.Model):50     """51     route table collect task table52     """53     device = models.ForeignKey(to=NcmdbRouterIpTable, null=True)54     task_time = models.DateTimeField(null=True)55     status = models.IntegerField(choices=TASK_STATUS)56     result = models.IntegerField(choices=TASK_RESULT, null=True, blank=True)57     task_id_celery = models.CharField(max_length=128, null=True, blank=True)58     start_time = models.DateTimeField(auto_now_add=True)59     finish_time = models.DateTimeField(auto_now=True)60 61     def __str__(self):62         return "{}:{}".format(self.__class__.__name__, self.task_id_celery)63 64     class Meta:65         db_table = "rtm_route_table_collect_task"
model代码
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3  4 import django_filters 5 from rest_framework import serializers 6 from apps.rtm.models import * 7 from apps.ncmdb.uilts.uilts import format_time 8  9 __all__ = ['RouteTableSerializer', 'RouteTableFilter']10 11 class RouteTableSerializer(serializers.ModelSerializer):12     create_time = serializers.SerializerMethodField()13     device = serializers.CharField(source="device.manage_ip")14 15     def get_create_time(self, row):16         return format_time(row.create_time) if row.create_time else None17 18     class Meta:19         model = RouterTable20         fields = ["subnet", "protocol", "vrf", "interface", "metric", "nexthop",21                   "preference", "device", "create_time"]22 23 24 class RouteTableFilter(django_filters.rest_framework.FilterSet):25     #method后跟的函数表示自定义筛选26     dc = django_filters.CharFilter(method='dc_filter', label="dc")27     manage_ip = django_filters.CharFilter(method='manage_ip_filter', label="manage_ip")28 29     def dc_filter(self, queryset, name, value):30         return queryset.filter(device__dc=value)31 32     def manage_ip_filter(self, queryset, name, value):33         return queryset.filter(device__manage_ip__icontains=value)34 35     class Meta:36         model = RouterTable37         fields = ("subnet", "protocol", "vrf", "nexthop", "preference", "manage_ip", "dc", "metric")
serializers及filter代码
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3  4 from rest_framework.viewsets import ModelViewSet 5 from apps.rtm.models import RouterTable 6 from apps.rtm.views.route_table_serializers import * 7 from utils.authencation_func import BaseAuth, Pagination 8 from django_filters.rest_framework import DjangoFilterBackend 9 from rest_framework.filters import OrderingFilter10 11 class RouteTableOperate(ModelViewSet):12     authentication_classes = [BaseAuth]13     queryset = RouterTable.objects.all()14     serializer_class = RouteTableSerializer15     pagination_class = Pagination16     #DjangoFilterBackend表示开启筛选,OrderingFilter表示开启排序17     filter_backends = [DjangoFilterBackend, OrderingFilter]18     filter_class = RouteTableFilter19     #ordering_fields='__all__'表示支持所有的字段排序, 默认是create_time降序20     # 再给字段传排序值时ordering=-create_time表示降序,ordering=create_time表示升序21     ordering_fields = '__all__'22     ordering = ('-create_time',)
Views代码

 

转载于:https://www.cnblogs.com/grub007/p/10071853.html

你可能感兴趣的文章
Yii用ajax实现无刷新检索更新CListView数据
查看>>
App 卸载记录
查看>>
南京大学周志华教授当选欧洲科学院外籍院士
查看>>
计算机网络与Internet应用
查看>>
Django 文件下载功能
查看>>
走红日本 阿里云如何能够赢得海外荣耀
查看>>
qt 学习之路2
查看>>
线上应用故障排查之二:高内存占用
查看>>
异常处理汇总 ~ 修正果带着你的Code飞奔吧!
查看>>
PCIE_DMA:xapp1052学习笔记
查看>>
python ----字符串基础练习题30道
查看>>
uva-10879-因数分解
查看>>
python 调用aiohttp
查看>>
跨域iframe高度自适应(兼容IE/FF/OP/Chrome)
查看>>
学习鸟哥的Linux私房菜笔记(8)——文件查找与文件管理2
查看>>
升级fedora 18到fedora 19
查看>>
11月20日学习内容整理:jquery插件
查看>>
SVN与TortoiseSVN实战:补丁详解
查看>>
获取页面中所有dropdownlist类型控件
查看>>
读《淘宝数据魔方技术架构解析》有感
查看>>