Monday, September 8, 2014

Query parameters in the URL, with REST Framework

Hi, everybody.

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.

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f2eb0566-b38c-44f4-8814-f93710d03cec%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment