我是DRF的新手,并且实现了基于类的视图,并且我尝试了一个示例示例
@api_view(['GET', 'POST'])
class ProductList(APIView):
print "inside"
def get_user_products(self, request, user_id, format=None):
products = Product.objects.all(user_id=user_id)
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
def get_seller_products(self, request, seller_id, format=None):
products = Product.objects.filter(seller_id=seller_id)
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
def post(self, request, user_id, seller_id, format=None):
serializer = ProductSerializer(data=request.DATA, context={'request':request})
if serializer.is_valid():
serializer.object.user = User.objects.get(id=user_id)
serializer.object.seller = Seller.objects.get(id=seller_id)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
我这个类用于我的产品apis,但我不知道如何访问各个方法来访问相应的结果,比如我如何点击get_user_products或get_seller_products
现在我称这个api为http://localhost:8000/products
作为GET方法执行这个类,它打印出“内部”,你可以看到,但我如何调用其中的方法
以下是此应用的url.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^login$', 'userapp.views.login_user', name="login"),
url(r'^products$', 'productapp.views.ProductList', name="product-list"),
]
答案 0 :(得分:2)
你不应该使用clearTimeout( id )
装饰器来装饰基于类的视图;您将api_view
与基于函数的视图一起使用。
如果要使用基于类的视图(如示例中的视图),请删除api_view
语句和print
装饰器,并通过导入视图将视图包含在urlconf中,并使用api_view
,如the tutorial所示。在您的情况下,urlconf可能如下所示:
ProductList.as_view()
另外,请记住,不推荐在urlpatterns中使用包含导入路径的字符串,并且在即将推出的Django版本中将删除对此的支持。而是在urlconf中导入所有视图,并直接使用视图函数,例如:
from productapp.views import ProductList
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^login$', 'userapp.views.login_user', name="login"),
url(r'^products$', ProductList.as_view(), name="product-list"),
]