Home > Net >  do we need query set in CreateAPIView?
do we need query set in CreateAPIView?

Time:12-29

My question is quite straight forward. I'm actually not sure that queryset is required need for CreateAPIView or not.. ?

class CreateNotificationAPIView(generics.CreateAPIView):
    """This endpoint allows for creation of a notification"""
    queryset = Notification.objects.all() #can we remove it, if we do so, will we face any issue in future ?
    serializer_class = serializers.NotificationSerializer

CodePudding user response:

No. The only HTTP method the CreateAPIView [drf-doc] offers is the POST method, and it implements this by making a call to the create method. The .create(…) method is implemented as [GitHub]:

def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

These methods only work with the serializer, or with self.perform_create and self.get_success_headers that by default only work with the data of the serializer.

If you thus not override the methods of the CreateAPIView to use the queryset somehow, you can define a CreateAPIView without defining a queryset or override get_queryset.

CodePudding user response:

according to REST_docs

queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests.

  • Related