My Product model has an extra field named "product_id" which is a uuid string. Now I can get the product details based on the primary key id. I want to change this to get the product details using "product_id" field.
My current urls.py
url(r'^products/(?P<pk>[0-9]+)/$', views.ProductDetailCustom.as_view(), name='product-detail'),
Now am calling like this.
http://127.0.0.1:8000/api/v1/products/1460
I want this should be like this.
http://127.0.0.1:8000/api/v1/products/04396134-3c90-ea7b-24ba-1fb0db11dbe5
views.py
class ProductDetailCustom(generics.RetrieveAPIView):
queryset = Product.objects.all()
serializer_class = ProductCustomSerializer
serializer.py
class ProductCustomSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('url', 'id','product_id', 'title', 'description','structure','date_created',)
I think I have to include a look field to achive this.
Add lookup_field
to product_id
:
class ProductDetailCustom(generics.RetrieveAPIView):
lookup_field = "product_id"
queryset = Product.objects.all()
serializer_class = ProductCustomSerializer
The lookup_field
would be used by the get_object
call which would retrieve the model instance. So you can write a custom get_object
method on your view.
Ref: http://www.django-rest-framework.org/api-guide/generic-views/#genericapiview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With