how use django rest framework create api when data model has composite key consisting of 2 fields? background: trying make rest api data model (sample data row below- first 2 entries make composite key). able call upon data date field getting errors when try use second string field return single record.
'2015-05-06','intc','31.93','32.79','32.50','32.22','31737537'
i trying make api url structure so:
localhost/api/v1/yyyy-mm-dd/'char'
localhost/api/v1/2015-05-07/aapl
serializers.py
from rest_framework import serializers .models import stocksusa, optionsusa rest_framework.reverse import reverse class stocksusaserializer(serializers.hyperlinkedmodelserializer): url = serializers.serializermethodfield('get_stock_usa_url') def get_stock_usa_url(self, obj): values = [obj.trade_date, obj.ticker] composite_key_url = "http://0.0.0.0:9978/api/v1/stocksusa/{}/{}".format(*values) return composite_key_url class meta: model = stocksusa fields = ('trade_date', 'ticker', 'pxmin', 'pxmax', 'pxopen', 'pxclose', 'volume', 'url')
views.py
from django.shortcuts import render rest_framework import authentication, permissions, viewsets, filters .models import stocksusa .serializers import stocksusaserializer django.contrib.auth import get_user_model user = get_user_model() class defaultsmixin(object): authentication_classes = ( authentication.basicauthentication, authentication.tokenauthentication, ) permission_classes = ( permissions.isauthenticated, ) paginate_by = 25 paginate_by_param = 'page_size' max_paginate_by = 100 filter_backends = ( filters.djangofilterbackend, filters.searchfilter, filters.orderingfilter, ) class stocksusaviewset(defaultsmixin, viewsets.readonlymodelviewset): queryset = stocksusa.objects.all() serializer_class = stocksusaserializer
app/urls.py
from rest_framework.routers import defaultrouter . import views router = defaultrouter(trailing_slash=false) router = defaultrouter() router.register(r'stocksusa', views.stocksusaviewset)
urls.py
from django.conf.urls import patterns, include, url django.contrib import admin django.conf.urls import include, url rest_framework.authtoken.views import obtain_auth_token findatausa.urls import router findatausa.views import stocksusaviewset stockview urlpatterns = patterns('', url(r'^api/token/', obtain_auth_token, name='api-token'), url(r'^api/v1/', include(router.urls)), url(r'^api/v2/', include(router.urls)), url(r'^admin/', include(admin.site.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^docs/', include('rest_framework_swagger.urls')), )
the problem lies fact defaultrouter uses id lookup_field of model getting object want: example works:
get localhost/api/v1/stocksusa/1
in order provide parameters need hand-craft urls 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 passed view kwargs dictionary:
self.kwargs['year'] self.kwargs['month'] self.kwargs['day'] self.kwargs['code']
on get_object method need 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 have access object:
Comments
Post a Comment