Please help me understand the principle of organizing request processing in Django REST. Here , for example, the basics are explained
GET /book/ — получить список всех книг GET /book/3/ — получить книгу номер 3 PUT /book/ — добавить книгу (данные в теле запроса) POST /book/3 – изменить книгу (данные в теле запроса) DELETE /book/3 – удалить книгу
With this it is clear – standard requests. But how do you get a book called "title1"? How do I delete a book with the same title? Those. how to add a filter? How can I add my own method that will be called, say, on
/book/3/status and return the status of a specific book? Moreover, so as not to overlap the standard methods described above. How do I implement this in Django REST? And is it even possible?
Here it is told about the principles of web-API in general And there is an example of such a request
Trying to reproduce:
GET /book/ returns a list of all books. But also
GET /book?id=1 also returns a list of all books
In my test case, in my urls.py:
class MyAPI(mixins.UpdateModelMixin, generics.ListCreateAPIView): model = Book permission_classes = [ permissions.IsAuthenticated ] def get_serializer_class(self): return BookSerializer def get_queryset(self): return self.model.objects.filter(user=self.request.user).order_by('order')
How do I add a filter?
You have a method that returns all books –
GET /book . It is logical that you need to search for a book by title among all books. According to this http://habrahabr.ru/post/181988/ manual, such parameters must be passed behind a question mark. This means that the url should get
GET /book?name=название1 title1, and in the method responsible for the return of all books, you need to check for the
name parameter and filter the selection from the database by its value:
if request.GET.get('name', None): Book.objects.filter(name=request.GET.get('name'))
The same with deletion, only the http method is different.
How do I get my status back?
If you return the status of a book to
/book/3/status , then what will the url look like for getting both the status and the price of the book? According to all the same recommendations from this http://habrahabr.ru/post/181988/ article, you do not need to do one method for each returned field. It is necessary to indicate what data about the book should be returned after the question mark:
/book/3?fields=status,price . In the code, we get the required fields
request.GET.get('fields') in the same way and give the client only what he asked for.