用djang rest framework写一个增删改查案例
时间: 2024-05-02 08:19:01 浏览: 90
增删改查实例
这里是一个使用Django Rest Framework实现的增删改查案例。
首先,创建一个Django项目并安装Django Rest Framework:
```
pip install djangorestframework
```
接下来,创建一个模型类:
```python
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.title
```
创建完成后,需要在`settings.py`中配置`INSTALLED_APPS`和`REST_FRAMEWORK`:
```python
# settings.py
INSTALLED_APPS = [
...
'rest_framework',
'books',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
}
```
接下来,创建一个序列化器来将模型转化为JSON格式:
```python
# serializers.py
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
```
在视图中,我们需要继承`APIView`类来处理HTTP请求:
```python
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Book
from .serializers import BookSerializer
class BookList(APIView):
def get(self, request):
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
def post(self, request):
serializer = BookSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class BookDetail(APIView):
def get_object(self, pk):
try:
return Book.objects.get(pk=pk)
except Book.DoesNotExist:
raise Http404
def get(self, request, pk):
book = self.get_object(pk)
serializer = BookSerializer(book)
return Response(serializer.data)
def put(self, request, pk):
book = self.get_object(pk)
serializer = BookSerializer(book, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk):
book = self.get_object(pk)
book.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
```
最后,需要在`urls.py`中定义路由:
```python
# urls.py
from django.urls import path
from .views import BookList, BookDetail
urlpatterns = [
path('books/', BookList.as_view(), name='book-list'),
path('books/<int:pk>/', BookDetail.as_view(), name='book-detail'),
]
```
现在,我们就可以使用这个API来进行增删改查操作了。例如,使用HTTP POST请求创建一本新书:
```
POST /books/
{
"title": "Python for Data Science",
"author": "John Smith",
"description": "A comprehensive guide to data science using Python"
}
```
使用HTTP GET请求获取所有书籍:
```
GET /books/
```
使用HTTP GET请求获取一本书籍:
```
GET /books/1/
```
使用HTTP PUT请求更新一本书籍:
```
PUT /books/1/
{
"title": "Python for Machine Learning",
"author": "John Smith",
"description": "A comprehensive guide to machine learning using Python"
}
```
使用HTTP DELETE请求删除一本书籍:
```
DELETE /books/1/
```
阅读全文