简体   繁体   English

从 urls.py 调用基于 Class 的视图 Django 的特定 function

[英]Call a particular function of Class based view Django from urls.py

I have this views.py where I've implemented Class based views, but let's say I want to call a function get_featured_products when the url is https://localhost:8000/featured_products .我在 views.py 中实现了基于 Class 的视图,但假设我想在 url 为https://localhost:8000/featured_products时调用 function get_featured_products What sould my urls.py look like to call the get_features_products function?我的 urls.py 看起来像什么叫get_features_products function?

from django.shortcuts import render
from rest_framework import views
from rest_framework.response import Response
from .models import * 
from .serializers import * 

# Create your views here.


class ProductView(views.APIView):
    model= Product
    serializer = ProductSerializer


    def get(self,request):
        qs = self.model.objects.all()
        serializer = self.serializer(qs, many=True)

        return Response(serializer.data)

    
    def post(self,request):
        serializer = self.serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)

        return Response(serializer.error_messages())


    def put(self,request,pk):
        product = Product.objects.get(id=pk)
        serializer = self.serializer(instance=product, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.error_messages)

   def get_featured_products(self,request):
        #some code here
        return None

How should I refer to get_featured_products in my urls.py我应该如何在我的urls.py中引用get_featured_products

You can list it as any other class-based view in your urls.py using .as_view() but you will always have to have queryset as a class variable in your class that inherits from views.APIView .您可以使用.as_view()urls.py中将其列为任何其他基于类的视图,但您始终必须将查询集作为queryset变量在 class 中继承自views.APIView

Your view has to be defined like this您的视图必须像这样定义

class ProductView(APIView):
    queryset = Product.objects.all() # Here put your own queryset, for me if I dont i get error

    def get(self, request):
        print("GET REQUEST")
        return Response({"hello" : "world"})
    
    # you can similarly define other methods such as post, put like you already have

And then in your urls.py然后在你的urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    # You'll obviously have to import it if it is not  in the same file
    path('featured_products', ProductView.as_view()) 
]

For any class-based view, the urls.py can only contain ProductView.as_view().对于任何基于类的视图,urls.py 只能包含 ProductView.as_view()。 It is not possible to directly refer to a method within a class.不能直接引用 class 中的方法。

as_view() function calls an instance of the class and returns a response based on the following methods:'get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace' as_view() function 调用 class 的实例并根据以下方法返回响应:'get'、'post'、'put'、'patch'、'delete'、'head'、'options'、'trace '

If your method doesn't match the above, as is the case, you will get a HTTPresponseNotAllowed error.如果您的方法与上述不匹配,那么您将收到 HTTPresponseNotAllowed 错误。

You may place the method within one of the allowed methods and make it run.您可以将该方法放在允许的方法之一中并使其运行。

You may check this link to know more: https://djangodeconstructed.com/2020/01/03/mental-models-for-class-based-views/您可以查看此链接以了解更多信息: https://djangodeconstructed.com/2020/01/03/mental-models-for-class-based-views/

You can make the method as static and refer to this method from urls.py as:您可以将方法设为 static 并从 urls.py 中引用此方法:

# views.py
class ProductView(views.APIView):

    @staticmethod
    def get_featured_products(request):
        #some code here
        return None
        

# urls.py        
urlpatterns = [
    path('featured_products', ProductView.get_featured_products)
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM