3

I want to achieve this in Django

  1. List all items
  2. Get only one item
def get(self, request, pk, format=None):
    if pk is not None:
         product = self.get_object(pk)
         serializer = ProductSerializer(product)
    else:
         products = Product.objects.all()
         serializer = ProductSerializer(products)
    return Response(serializer.data)

If pk is in URL take only one product if not take all list.

How can I achieve that in URL? What I'm doing is this

re_path(r"(?P<pk>\d+)", ProductView.as_view(), name="product"),

But 'pk' argument is required here. I don't want the pk to be required but optional.

Thanks in advance

1 Answer 1

6

Define two paths:

urlpatterns = [
    path('/', ProductView.as_view(), {'pk': None}, name='products'),
    path('<int:pk>/', ProductView.as_view(), name='product'),
    # …
]

The {'pk': None} part specifies what value to pass.

An alternative is to make the pk optional, so:

def get(self, request, pk=None, format=None):
    if pk is not None:
         product = self.get_object(pk)
         serializer = ProductSerializer(product)
    else:
         products = Product.objects.all()
         serializer = ProductSerializer(products, many=True)
    return Response(serializer.data)

then you make again two paths with:

urlpatterns = [
    path('/', ProductView.as_view(), name='products'),
    path('<int:pk>/', ProductView.as_view(), name='product'),
    # …
]
Sign up to request clarification or add additional context in comments.

4 Comments

When I add two paths, in swagger the APIs are being duplicated
@maca: the proper way to do this is therefore not to use get twice, but simply make a ModelViewSet, that will point to different methods...
@maca: see django-rest-framework.org/api-guide/viewsets By doing that, the two really point to different methods, hence with different documentation.
@maca: the routers then define several paths that will point to retrieve and get django-rest-framework.org/api-guide/routers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.