如何在Django Rest框架中的通用API视图中访问url kwargs(更具体地讲ListCreateAPIView)? [英] How to access url kwargs in generic API views (ListCreateAPIView to be more specific) in django rest framework?
问题描述
如何在django rest框架的通用API视图(更具体地讲ListCreateAPIView)中访问url kwargs,例如
说我想覆盖 get_queryset()
通用APIView类中的方法,我希望它使用从url kwargs中提取的值,我该怎么做?
How to access url kwargs in generic API views (ListCreateAPIView to be more specific) in django rest framework,
for example say I want to override the get_queryset()
method inside a generic APIView class and I want it to use values as extracted from url kwargs, how would I do this?
推荐答案
leelum1 和 aman kumar 的答案对我有很大帮助,因为我有同样的问题。我将添加一个有关如何使用他们的答案的特定示例。在下面的代码中,我尝试获取所有具有 category
属性的产品,并在 cat
变量上传递相同的字符串
Answers from leelum1 and aman kumar helped me a lot, since I had the same question. I would add a particular example of how I used their answers. In the code below I try to obtain all the products that have as category
attribute the same string passed on the cat
variable from the url.
class ListProductsView(generics.ListCreateAPIView):
serializer_class = ProductSerializer
def get_queryset(self):
queryset = Product.objects.filter(category=self.kwargs['cat'])
return queryset
这解决了我使用url中的变量过滤对象的问题。
That solved my problem of filtering objects by using variables from the url.
这篇关于如何在Django Rest框架中的通用API视图中访问url kwargs(更具体地讲ListCreateAPIView)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!