'Optional parameters in django urls
I want to achieve this in Django
- List all items
- 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
