django_filters JSONField

实际需求:

django rest framework 根据多个字段中的一个值或者多个值的设定,来过滤结果,并返回给前端

具体实现代码:

from django.db import models
from django_mysql.models import JSONField
……
models.py:
class CVMSets(models.Model):
    CVM_id = models.AutoField(primary_key=True)
    Placement = JSONField(null=True, blank=True)
    InstanceId = models.CharField(
        max_length=200, unique=True, null=False, blank=False)
    InstanceType = models.CharField(max_length=20)
    CPU = models.IntegerField()
    Memory = models.IntegerField()
    RestrictState = models.CharField(max_length=20)
    InstanceName = models.CharField(max_length=100)
    InstanceChargeType = models.CharField(max_length=20)
    SystemDisk = JSONField(null=True, blank=True)
    DataDisks = JSONField(null=True, blank=True)
    PrivateIpAddresses = JSONField(null=True, blank=True)

from backend.models import *
from rest_framework import serializers
……
serializers.py:
class CVMSetsSerializer(serializers.HyperlinkedModelSerializer):
    custom_ProjectId = serializers.SerializerMethodField()

    def get_custom_ProjectId(self, obj):
        return PlatformSets.objects.get(pk=obj.Placement['ProjectId']).Name if obj.Placement['ProjectId'] else None

    class Meta:
        model = CVMSets
        fields = ['url', 'CVM_id', 'Placement', 'InstanceId', 'InstanceType', 'CPU', 'Memory', 'RestrictState', 'InstanceName', 'InstanceChargeType', 'SystemDisk', 'DataDisks', 'PrivateIpAddresses', ]

from backend.models import *
from rest_framework.views import APIView
from django_filters import rest_framework as filters
……
views.py:

class CVMSetsFilter(filters.FilterSet):
    PrivateIpAddresses = filters.CharFilter(
        field_name='PrivateIpAddresses', lookup_expr='contains')

    class Meta:
        model = CVMSets
        fields = ['InstanceId', 'InstanceName', 'PrivateIpAddresses']

class CVMSetsViewSet(viewsets.ModelViewSet):
    queryset = CVMSets.objects.all()
    serializer_class = CVMSetsSerializer
    filter_class = CVMSetsFilter

You may also like...