django序列化使用ModelSerializer

 

models.py

from django.db import models
import django.utils.timezone as timezone


# Create your models here.
class HostList(models.Model):
    id = models.BigAutoField(primary_key=True,verbose_name='自增id',help_text='自动增长ID')
    ip = models.CharField(verbose_name='ip地址',null=True,max_length=32)
    remark = models.CharField(verbose_name='描述',null=True,max_length=128)
    create_time = models.DateTimeField(verbose_name='创建时间', default=timezone.now)
    modify_time = models.DateTimeField(verbose_name='更新时间', default=timezone.now)

    class Meta:
        # app_label = "rdsapp"
        db_table = "tb_host_info"
        verbose_name = "主机信息表"
        verbose_name_plural = '主机信息表'

 

serializers.py

该文件默认是不存在的,需要自己创建

from rest_framework import serializers
from .models import HostList


class HostListModelSerializers(serializers.ModelSerializer):
    class Meta:
        model = HostList
        fields = '__all__'

 

views.py

from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
import json
from django.http import HttpResponse
import paramiko
from .models import HostList
from .serializers import HostListModelSerializers
from .import models



def get_hostlist(request):
    hostlist = HostList.objects.all()
    serializer = HostListModelSerializers(hostlist, many=True)
    res_list= []
    iplist = serializer.data
    total = len(iplist)
    current = request.GET.get("current", 1)
    size = request.GET.get("size", 0)

    print('current=', current)
    print('size=', size)

    if current and size:
        end = int(current) * int(size)
        start = (int(current) - 1) * int(size)
        iplist = iplist[start:end]

    for ip in iplist:
        res_list.append(ip)

    res = {
        "data": {
            "list": res_list,
            "total": total
        },
        "result": True
    }
    return JsonResponse(res, safe=False)

 

urls.py

from django.conf.urls import url
from django.urls import path, re_path
from apphost import views

urlpatterns = [
    path('get_hostlist/', views.get_hostlist)
]

 

postman调用

 

若不使用序列化,定义模型的时候需要定义to_dic函数

 

views.py通过如下使用

 

posted @ 2024-10-23 15:42  slnngk  阅读(7)  评论(0编辑  收藏  举报