[Answer]-Using Django REST Framework API for data model with composite key

1👍

The problem lies into the fact that the DefaultRouter uses the id lookup_field of your model for getting the object you want: For example this works:

GET   localhost/api/v1/stocksusa/1

In order to provide extra parameters you need to hand-craft the urls like this:

 url(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})/(?P<code>\w+)$',
    StocksUsaViewSet.as_view(),
    name='stocks_detail'
),

The year month day code parameters are passed into your view with the kwargs dictionary:

self.kwargs['year']
self.kwargs['month']
self.kwargs['day']
self.kwargs['code']

On your get_object method you need to do something like that:

def get_object(self, queryset=None):
    try:
        date= datetime.date(
            year=int(self.kwargs['year']),
            month=int(self.kwargs['month']),
            day=int(self.kwargs['day']),
        )
    except ValueError:
        raise Http404
    stock= get_object_or_404(Stocksusa, Ticker=self.kwargs['code'], Trade_Date=date)
    return stock

Then you will have access to your object:

Leave a comment