I, stared using REST Framework few days ago, but I, can't find how create a customized url with parameter, in Django this kind of url is written like this.
url(r'^author/(?P<author>\d+)/books/$', BooksList.as_view(), name = 'books'),
for this
http://mysite/author/1/books
I, try with:
router.register(r'author/(?P<author>\d+)/books', BooksList, base_name = 'Books')
but this don't work.
I, see this questions but, don't work: question 1 question 2
This is my code.
# models.py
class Author(models.Model):
Name = models.CharField(max_length = 50)
class Book(models.Model):
Book = models.ForeignKey(Author)
Title = models.CharField(max_length = 200)
def __unicode__(self):
return self.Title
# views.py
class BooksList(viewsets.ModelViewSet):
model = Book
serializer_class = BookSerializer
def get_queryset(self):
author = self.kwargs['author']
queryset = Book.objects.filter(Author = author)
return queryset
# urls.py
router = routers.DefaultRouter()
router.register(r'books', BooksList, base_name = 'Books')
admin.autodiscover()
urlpatterns = patterns('',
url(r'^api/', include('rest_framework.urls', namespace = 'rest_framework')),
)
I solved this reading the tutorial in second part "Adding optional format suffixes to our URLs",
At, last I get url like this:
http://localhost:8001/books/author/1/
Here is my code.
# urls.py
url(r'^books/author/(?P<author>\d+)/$', BooksByAuthor, name='BooksByAuthor'),
# serializer.py
class BooksSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'Title')
# views.py
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from .serializers import *
class JSONResponse(HttpResponse):
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
def BooksByAuthor(request, author):
try:
books = Book.objects.filter(Author = author).order_by('Title')
except Book.DoesNotExist:
return HttpResponse(status=400)
if request.method == 'GET':
serializer = BooksSerializer(books)
return JSONResponse(serializer.data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With