Django过滤器无法正常工作

时间:2016-06-08 06:02:38

标签: django python-3.x django-rest-framework django-filter

我的过滤器不工作每当我访问http://localhost:8080/payables/invoices/?status=NOT_PAID它只返回所有发票。我没有运行时错误,我输入的参数似乎只是被忽略了。我真的不明白,除此之外,它运作良好。

views.py

class InvoiceViewSet(viewsets.ViewSet):
    serializer_class = InvoiceSerializer
    filter_backend = filters.DjangoFilterBackend
    filter_fields = ('status','supplier',)

    def list(self,request,):
        queryset = Invoice.objects.filter()
        serializer = InvoiceSerializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        queryset = Invoice.objects.filter()
        invoice = get_object_or_404(queryset, pk=pk)
        serializer = InvoiceSerializer(invoice)
        return Response(serializer.data)

class InvoiceItemViewSet(viewsets.ViewSet):

    serializer_class = InvoiceItemSerializer

    def list(self,request,invoice_pk=None):
        queryset = InvoiceItem.objects.filter(invoice=invoice_pk)
        serializer = InvoiceItemSerializer(queryset,many=True)
        return Response(serializer.data)


    def retrieve(self,request,pk,invoice_pk):
        queryset = InvoiceItem.objects.filter(pk=pk,invoice=invoice_pk)
        invoice_item = get_object_or_404(queryset,pk=pk)
        serializer = InvoiceItemSerializer(invoice_item)
        return Response(serializer.data)

url.py

from django.conf.urls import url, include
#viewset
from rest_framework_nested import routers
from payables.views import InvoiceViewSet,InvoiceItemViewSet

router = routers.SimpleRouter()
router.register(r'invoices', InvoiceViewSet,base_name='invoices')

invoice_item_router = routers.NestedSimpleRouter(router,r'invoices',lookup='invoice')
invoice_item_router.register(r'items', InvoiceItemViewSet, base_name='invoice_items')

urlpatterns = [
    url(r'^',include(router.urls)),
    url(r'^',include(invoice_item_router.urls))
    ]

3 个答案:

答案 0 :(得分:2)

这是因为您显式创建了查询集,因此永远不会使用过滤后端:

queryset = Invoice.objects.filter()

我建议查看ModelViewSet。在这种情况下,你只需要在视图级别传递queryset并休息。

答案 1 :(得分:1)

而不是queryset = Invoice.objects.filter()

使用queryset = self.get_queryset()

self.get_queryset()返回过滤后的对象列表

答案 2 :(得分:0)

代替implementation 'androidx.legacy:legacy-support-v4:1.0.0-alpha1' { exclude group: 'com.android.support' exclude module: 'support-v4' }

queryset = Invoice.objects.filter()