Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework: Get detail view using a field other than primary key integer id

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.

like image 609
Arun SS Avatar asked Apr 17 '17 11:04

Arun SS


1 Answers

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

like image 171
masnun Avatar answered Oct 16 '22 21:10

masnun