3
我正在使用django rest框架,我想用自定義方法訂購。Django Rest訂購定製
所以,當我把這個網址,例如:http://127.0.0.1:8000/api/sets/?ordering=partMissing
有可能調用自定義的方法,因爲我想與秩序的一部分,由片段缺失的數量。我計算了多對多領域中的部分數量之和。
非常感謝您的回答。
我正在使用django rest框架,我想用自定義方法訂購。Django Rest訂購定製
所以,當我把這個網址,例如:http://127.0.0.1:8000/api/sets/?ordering=partMissing
有可能調用自定義的方法,因爲我想與秩序的一部分,由片段缺失的數量。我計算了多對多領域中的部分數量之和。
非常感謝您的回答。
我有非常簡單的POC,應該允許你實現更復雜的解決方案。
views.py
from rest_framework import viewsets
from ordering_test.models import Test
from ordering_test.ordering import MyCustomOrdering
from ordering_test.serializers import TestSerializer
class TestViewSet(viewsets.ModelViewSet):
queryset = Test.objects.all()
serializer_class = TestSerializer
filter_backends = (MyCustomOrdering,)
ordering.py
from rest_framework.filters import OrderingFilter
class MyCustomOrdering(OrderingFilter):
allowed_custom_filters = ['testMethod']
def get_ordering(self, request, queryset, view):
"""
Ordering is set by a comma delimited ?ordering=... query parameter.
The `ordering` query parameter can be overridden by setting
the `ordering_param` value on the OrderingFilter or by
specifying an `ORDERING_PARAM` value in the API settings.
"""
params = request.query_params.get(self.ordering_param)
if params:
fields = [param.strip() for param in params.split(',')]
# care with that - this will alow only custom ordering!
ordering = [f for f in fields if f in self.allowed_custom_filters]
if ordering:
return ordering
# No ordering was included, or all the ordering fields were invalid
return self.get_default_ordering(view)
def filter_queryset(self, request, queryset, view):
ordering = self.get_ordering(request, queryset, view)
if ordering:
# implement a custom ordering here
ordering = ['-id']
if ordering:
return queryset.order_by(*ordering)
return queryset
的models.py和serializers.py很簡單,但在這裏把它:
models.py
從django.db進口車型
class Test(models.Model):
test = models.CharField(max_length=120)
test1 = models.CharField(max_length=120)
serializers.py
from rest_framework import serializers
from ordering_test.models import Test
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = Test
fields = ('test', 'test1')
編碼愉快!
謝謝。你是天才!我明天測試。 –