Bootstrap

python serializer, model drf通过序列化器, 模型获取mysql 一张表某个字段数据库现存的最大值

需求, 我想获取pbr_config这张表seq_num 意为序号最大值

核心代码如下:

方法一:

        max_seq_num = PolicyRoutingConfig.objects.aggregate(Max('seq_num'))['seq_num__max']  # 获取数据库最大序号 无数据时返回{'seq_num__max': None}
        request.data['seq_num'] = max_seq_num + 1 if max_seq_num else 1  # 若为None,则从1开始

用到了Max函数, 需要导入

from django.db.models import  Max依赖

方法二:

policy = PolicyRoutingConfig.objects.all().order_by('-seq_num').first()
max_seq_num = policy.seq_num
sqe_num = max_seq_num + 1  if max_seq_num else 1
seq_num = policy.seq_num + 1  # 新建这一条策略的序号
# serializer.validated_data['seq_num'] = seq_num

# serializer.save()

model模型核心代码

from django.db import models
class PolicyRoutingConfig(models.Model):
    """策略路由"""
    pbr_id = models.AutoField(auto_created=True, primary_key=True, blank=True, serialize=False, help_text='策略路由序号即数据库自增id')
    seq_num = models.IntegerField(blank=True, help_text='拖拽相关参数, 序号')
    src_addr = models.CharField(max_length=64, help_text='源地址,默认any,可选择地址对象和地址组或手动输入ip/mask')
    dst_addr = models.CharField(max_length=64, help_text='目的地址,默认any,可选择地址对象和地址组或手动输入ip/mask')
    service = models.CharField(max_length=64, help_text='服务, 默认any,可选择服务和服务组')
    gateway_addr = models.CharField(max_length=64, help_text='网关地址')
    gateway_weight = models.IntegerField(default=1, help_text='网关的权重值')
    gateway_interface = models.CharField(max_length=64, help_text='网关关联的接口名称')
    priority = models.IntegerField(default=1, help_text='优先级')
    enable = models.IntegerField(help_text='是否启用 0:关闭 1:启用')

    class Meta:
        managed = True
        db_table = 'pbr_config'
        app_label = 'netset'

序列化器类核心代码

from rest_framework import serializers
from netset.models import PolicyRoutingConfig

class PolicyRoutingSerializer(serializers.ModelSerializer):
    """策略路由配置"""
    class Meta:
        model = PolicyRoutingConfig
        fields = ('pbr_id', 'seq_num', 'src_addr', 'dst_addr', 'service', 'gateway_addr', 'gateway_weight',
                  'gateway_interface', 'priority', 'enable')

 

;