Home > database >  Optional parameters in django urls
Optional parameters in django urls

Time:03-01

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

CodePudding user response:

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'),
    # …
]
  • Related