model
1 2 3 4 5 6 7 8 9 10 |
class ServicePod(models.Model): service_name = models.CharField(max_length=255) pod_ip = models.CharField(max_length=255) function = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # Add other fields as necessary def __str__(self): return f"{self.service_name} - {self.pod_ip}" |
serilazer:
1 2 3 4 |
class ServicePodSerializer(serializers.ModelSerializer): class Meta: model = ServicePod fields = ['id', 'service_name', 'pod_ip', 'function', 'created_at', 'updated_at'] # Include other fields here |
path:
1 2 3 4 5 6 7 |
from rest_framework import routers from .views import ServicePodViewSet router = routers.DefaultRouter() # router.register(r'', ) # router.register(r'servicepods', ServicePodViewSet) router.register(r'servicepods', ServicePodViewSet) |
views:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# views.py from rest_framework import viewsets, filters from rest_framework.pagination import PageNumberPagination from .models import ServicePod from .serializers import ServicePodSerializer class ServicePodPagination(PageNumberPagination): page_size = 2 page_size_query_param = 'page_size' max_page_size = 100 class ServicePodViewSet(viewsets.ModelViewSet): queryset = ServicePod.objects.all() serializer_class = ServicePodSerializer pagination_class = ServicePodPagination filter_backends = [filters.SearchFilter] search_fields = ['service_name', 'pod_ip'] # Specify searchable fields |
测试:
Get the first page: http://127.0.0.1:8000/api/servicepods/
Get the second page: http://127.0.0.1:8000/api/servicepods/?page=2
Search by service_name: http://127.0.0.1:8000/api/servicepods/?search=example_service_name
Search by pod_ip: http://127.0.0.1:8000/api/servicepods/?search=example_pod_ip