Skip to content
Browse files

Expose full model to API

  • Loading branch information
andrewdotn committed Aug 20, 2016
1 parent 727df51 commit 5d9b19184e444f2d38d2ccec9c53b9d9b431b9a1
Showing with 37 additions and 6 deletions.
  1. +7 −1 polls_rest/polls/
  2. +23 −2 polls_rest/polls/
  3. +7 −3 polls_rest/polls/
@@ -2,6 +2,12 @@

from .models import Choice, Question

class QuestionSerializer(serializers.ModelSerializer):
class ChoiceSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Choice

class QuestionSerializer(serializers.HyperlinkedModelSerializer):
choice_set = ChoiceSerializer(many=True)

class Meta:
model = Question
@@ -1,11 +1,32 @@
from django.conf.urls import include, url

from rest_framework import routers
from django.urls.exceptions import NoReverseMatch

from . import views

from rest_framework import reverse, routers

# Monkey patch namespace support into Django REST framework
ORIG_REVERSE = reverse._reverse
def namespace_aware_reverse(viewname, args=None, kwargs=None, request=None,
format=None, **extra):
"""If reverse fails, try again using the namespace under which the current
request was found.
To be monkey-patched into rest_framework.reverse._reverse"""
return ORIG_REVERSE(viewname, args=args, kwargs=kwargs, request=request,
format=format, **extra)
except NoReverseMatch:
viewname = request.resolver_match.namespace + ':' + viewname
return ORIG_REVERSE(viewname, args=args, kwargs=kwargs, request=request,
format=format, **extra)
reverse._reverse = namespace_aware_reverse


api_router = routers.DefaultRouter()
api_router.register(r'questions', views.QuestionViewSet)
api_router.register(r'choices', views.ChoiceViewSet)

app_name = 'polls'
urlpatterns = [
@@ -1,12 +1,12 @@
from django.db.models.expressions import F
from django.http import HttpResponse, HttpResponseRedirect
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from rest_framework import viewsets

from .models import Choice, Question
from .serializers import QuestionSerializer
from .serializers import ChoiceSerializer, QuestionSerializer

def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
@@ -40,3 +40,7 @@ def vote(request, question_id):
class QuestionViewSet(viewsets.ModelViewSet):
queryset = Question.objects.all()
serializer_class = QuestionSerializer

class ChoiceViewSet(viewsets.ModelViewSet):
queryset = Choice.objects.all()
serializer_class = ChoiceSerializer

0 comments on commit 5d9b191

Please sign in to comment.
You can’t perform that action at this time.