2

マイ製品モデルには、uuid文字列である "product_id"という追加フィールドがあります。今、主キーIDに基づいて製品の詳細を取得できます。私はこれを変更して、 "product_id"フィールドを使って製品の詳細を取得します。Django rest framework:プライマリキーの整数ID以外のフィールドを使用して詳細ビューを取得

私の現在のurls.py

url(r'^products/(?P<pk>[0-9]+)/$', views.ProductDetailCustom.as_view(), name='product-detail'), 

は次のように呼び出しています。

http://127.0.0.1:8000/api/v1/products/1460 

これはこのようにする必要があります。

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',) 

私はこれをachiveルックフィールドを含めることがあると思います。

答えて

2

product_idlookup_fieldを追加します。

class ProductDetailCustom(generics.RetrieveAPIView): 
    lookup_field = "product_id" 
    queryset = Product.objects.all() 
    serializer_class = ProductCustomSerializer 

lookup_fieldは、モデルのインスタンスを取得しますget_objectコールで使用されます。だからあなたのビューにカスタムget_objectメソッドを書くことができます。

Ref:http://www.django-rest-framework.org/api-guide/generic-views/#genericapiview

+0

urls.pyではどのような変更が必要ですか?実際にはstringをproduct_idとして呼び出す必要があります。 –

+0

正規表現を変更して、 'product_id'を受け入れることができるようにします。今のところそれは数字だけを受け入れるようですか? – masnun

+0

この方法ですか? ' –

関連する問題