Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optional parameters in django urls

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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'),
    # …
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading