使用REST Framework查询URL中的参数

时间:2014-09-08 19:46:57

标签: django rest deserialization

我几天前盯着使用REST Framework,但是我无法找到如何使用参数创建自定义网址,在Django中这种网址是这样编写的。

url(r'^author/(?P<author>\d+)/books/$', BooksList.as_view(), name = 'books'),

这个

http://mysite/author/1/books

我试试:

router.register(r'author/(?P<author>\d+)/books', BooksList, base_name = 'Books')

但这不起作用。

我,看到这个问题,但是,不能工作: question 1 question 2

这是我的代码。

# 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 个答案:

答案 0 :(得分:2)

我在第二部分&#34; Adding optional format suffixes to our URLs&#34;,

中解读了本教程

At,最后我得到这样的网址:

http://localhost:8001/books/author/1/

这是我的代码。

# 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)