[Efficiency Platform] Configuration Management Module – Obtain configuration list data, view configuration detail data, add and update configuration, delete configuration related function development (9)

Hits: 0

1. Page display

1. Configuration list page display

2. New configuration page display

Second, define the model class

from django.db import models

# Create your models here.

from django.db import models

from utils.base_models import BaseModel


class  Configures (BaseModel) : 
    name = models.CharField( 'Configuration name' , max_length= 50 , help_text= 'Configuration name' )
    interface = models.ForeignKey('interfaces.Interfaces',
                                  on_delete=models.CASCADE,
                                  related_name='configures',
                                  help_text= 'belonging to the interface' )
    author = models.CharField( 'author' , max_length= 50 , help_text= 'author' )
    request = models.TextField( 'Request information' , help_text= 'Request information' )

    class  Meta : 
        db_table = 'tb_configures' 
        verbose_name = 'configuration information'
        verbose_name_plural = verbose_name
        ordering = ('id',)

    def __str__(self):
        return self.name

Third, define [the serializer] class

According to the list page, you need to output the configuration id, configuration name, project, interface, and author.
According to the add use case page, you need to enter the project id, interface id, request information, author, and configuration name.

1. There is no direct relationship between the project table and the use case table, so they cannot be directly associated, so the interface table needs to be used to associate them.
2. When one serializer class needs some fields in another serializer, it is necessary to customize the serializer class Use it as a field in another serializer
3. Pay attention to pid and iid. The output is the project name and interface name, and the input is the project id and interface id
. 4. PID and iid need to be checked Whether there is this data in the interface table, check whether there is this data in the project table by pid; b. It is necessary to verify whether id=iid and project_id=pid exist in the interface table)
5. The to_internal_value method is that all fields have passed the verification last method to execute

from rest_framework import serializers
from configures.models import Configures
from interfaces.models import Interfaces
from projects.models import Projects

def test_pid(value):
    count=Projects.objects.filter(id=value).count()
    if  not count:
         raise serializers.ValidationError( 'pid does not exist' )
     return value

def test_iid(value):
    count=Interfaces.objects.filter(id=value).count()
    if  not count:
         raise serializers.ValidationError( 'iid does not exist' )
     return value

class  InterfacesProjectsModelSerializer (serializers.ModelSerializer) : 
    project=serializers.StringRelatedField(label= 'name of the project to which the interface belongs' , help_text= 'name of the project to which the interface belongs' , read_only= True )
    pid=serializers.IntegerField(label= 'The id of the project to which the interface belongs' ,
                                help_text= 'The project id to which the interface belongs' ,
                                write_only=True,
                                validators=[test_pid])
    iid=serializers.IntegerField(label= 'interface id' ,
                                help_text= 'interface id' ,
                                write_only=True,
                                validators=[test_iid])

    class Meta:
        model=Interfaces
        fields=['name','project','pid','iid']
        extra_kwargs={
            'name':{
                'read_only':True
            }
        }

    def validate(self, attrs):
        iid=attrs.get('iid')
        pid=attrs.get('pid')
        count=Interfaces.objects.filter(id=iid,project_id=pid).exists()
        if  not count:
             raise serializers.ValidationError( 'pid and iid do not match' )
         return attrs


class  ConfiguresModelSerializer (serializers.ModelSerializer) : 
    interface=InterfacesProjectsModelSerializer(label= 'Interface Information' ,help_text= 'Interface Information' )
     class  Meta :
        model=Configures
        exclude=['create_time','update_time']
        extra_kwargs={
            'request':{
                'write_only':True
            }
        }

    def to_internal_value(self, data):
        response=super().to_internal_value(data)
        iid=response['interface']['iid']
        response['interface_id']=iid
        response.pop('interface')
        return response

Fourth, define the view

class ConfiguresViewSet(ModelViewSet):
    queryset=Configures.objects.all(is_delete=False)
    serializer_class=ConfiguresModelSerializer
    pagination_class=PageNumberPagination
    permission_classes=[permission.IsAuthenticated]
    ordering_fields=['id','name']

    def retrieve(self,request,*args,**kwargs):
        config_obj=self.get_object()
        config_request=json.loads(config_obj.request,encoding='utf-8')

        #Process request header data 
        config_headers=config_request[ 'config' ][ 'request' ].get( 'headers' )
        config_headers_list=handle_datas.handle_data4(config_headers)

        # Process global variable data 
        config_variables = config_request[ 'config' ].get( 'variables' )
        config_variables_list = handle_datas.handle_data2(config_variables)

        config_name = config_request['config']['name']
        selected_interface_id = config_obj.interface_id
        selected_project_id = Interfaces.objects.get(id=selected_interface_id).project_id

        data = {
            "author": config_obj.author,
            "configure_name": config_name,
            "selected_interface_id": selected_interface_id,
            "selected_project_id": selected_project_id,
            "header": config_headers_list,
            "globalVar": config_variables_list
        }
        return Response(data)

    def  perform_desroy (self,instance) : 
        instance.is_delete= True        #Soft delete, no real deletion 
        instance.save()

5. Define the route

from django.urls import path, include
from rest_framework import routers

from configures.views import ConfiguresViewSet

router=routers.SimpleRouter()
router.register(r'configures',ConfiguresViewSet)

urlpatterns=[
    path('',include(router.urls))
]

You may also like...

Leave a Reply

Your email address will not be published.