gpt4 book ai didi

Django过滤器不起作用

转载 作者:行者123 更新时间:2023-12-04 02:11:28 32 4
gpt4 key购买 nike

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

View .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))
]

最佳答案

这是因为您明确创建了查询集,因此从未使用过滤器后端:

queryset = Invoice.objects.filter()

我建议看 ModelViewSet .在这种情况下,您只需通过 queryset在 View 级别和休息将得到照顾。

关于Django过滤器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37694385/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com