简体   繁体   中英

Filtering with wildcards in Django Rest Framework

I'm looking for a way to be able to filter my dataset in DRF using a wildcard. For example; I want to return any hostname in the below model that starts with 'gb'. I also have some requirements to search in the middle and the end of the hostname depending on usecase.

I'd expect to be able to hi the following endpoint: /devices/?host_name=gb* and it return everything that has a host_name starting with gb.

Model:

class Device(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    host_name = models.CharField(max_length=64)
    mgmt_ip_address = models.GenericIPAddressField()
    domain_name = models.CharField(max_length=64)

    class Meta:
        ordering = ['host_name']

    def __str__(self):
        return self.host_name

Serializer:

class DeviceSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.ReadOnlyField()

    class Meta:
        model = Device
        fields = '__all__'

View:

class DeviceViewSet(viewsets.ModelViewSet):
    permission_classes = (DjangoModelPermissions,)
    queryset = Device.objects.all()
    serializer_class = DeviceSerializer
    filter_backends = [DjangoFilterBackend, filters.rest_framework.DjangoFilterBackend, drf_filters.SearchFilter]
    filter_fields = ['id',
                     'host_name',
                     'mgmt_ip_address',
                     ]

I have tried creating custom filters but not sure that is the right approach since I haven't been able to get it working.

Use Django startswith on the host_name field.

class DeviceListView(ListAPIView):
permission_classes = (DjangoModelPermissions,)
api_view = ['GET', ]
serializer_class = DeviceSerializer

def get_queryset(self):
    host_name = self.request.query_params.get("host_name", None)
    return Device.objects.filter(host_name__startswith=host_name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM