5

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

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.