How to use the same url and class for put, get, post, delete functions in drf class base api

PHPz
Release: 2024-02-08 20:45:13
forward
440 people have browsed it

如何在 drf 类基础 api 中对 put、get、post、delete 函数使用相同的 url 和类

Question content

In my view file I want this logic:

Articles (apiview):

def get(self, reqeust, id):
    #logic
def put(self, request, id):
    #logic  
def post(self, requst, id):
    #logic
def delete(self, request, id):
    #logic
Copy after login

I want a handle URL like this:

/articles/int:pk # Display articles with id=pk /articles/add # Add articles to the database etc...

But I have a question, I don't want to use different classes for different urls, at the same time I want if I call /articles/add , post method call, what is the best way to achieve this?

sry, I'm very new to python and drf, I would appreciate help on the best way to do this,

Am I going about this completely wrong? I just don't want to use drf in the apiview method to provide a different class for each post, get...


Correct Answer


What you describe here already exists: i.e. ViewSet [drf-doc]. This combines different methods in the same class. Usually, use the same serializer etc. So it groups logically what is often very similar.

In order to route items correctly, Router [drf-doc] is used to make the corresponding path. Some have primary keys, such as GET, PUT, PATCH, and DELETE, while POST does not. You can then customize it further.

The above is the detailed content of How to use the same url and class for put, get, post, delete functions in drf class base api. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template