I am trying to make an ecommerce project and I already set up products page, but It should load a product description page after goint to api/products/2 page, example(2 is a product id). views.py:
@api_view(['GET'])
def getProduct(request, pk):
product = None
for i in products:
if i['_id'] == pk:
product = i
break
return Response(product)
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.getRoutes, name="routes"),
path('products/', views.getProducts, name="products"),
path('prodcucts/<str:pk>/', views.getProduct, name="product"),
]
I already tried int:pk instead of str:pk
CodePudding user response:
At first check whether you need <str:pk>
or <int:pk>
as "2"
and 2
is treated differently in Python.
Then try this:
@api_view(['GET'])
def getProduct(request, pk):
product = ""
for i in products:
if i['_id'] == pk:
product = i
return Response(Product)
Edit:
The path name path('prodcucts/<str:pk>/'...
seems incorrect kindly check it.
CodePudding user response:
You are declaring products = None
and then you iterate with a for loop through products
. That results in iterating over None
Try to go for something like this:
from .your_model_module import Product
@api_view(['GET'])
def getProduct(request, pk):
product = Product.objects.get(id=pk)
return Response(product)
First you need to import your model. Then you do a get
query within all these Product objects that are stored in your database. The get
query will result in an error (if not found matching object or when multiple objects are found) or will return one object.
If you want to allow that multiple objects are getting found, replace get
with filter
lookup.
Also stick to your int:pk