RESTFul Add, delete, change and query interface of style
1、 Get all the information
establish model
from django.db import models
# Create your models here.
class Book(models.Model):
name = models.CharField(max_length=20)
price = models.IntegerField()
pub_date = models.DateField()
class BookInfo(models.Model):
btitle = models.CharField(max_length=20, verbose_name=' name ')
bpub_date = models.DateField(verbose_name=' Release time ')
bcomment = models.IntegerField(default=0, verbose_name=' Comment quantity ')
is_delete = models.BooleanField(default=False, verbose_name=' Logical deletion ')
class Meta:
db_table = 'tb_books' # Indicates the database table name
verbose_name = ' The book ' # stay admin The name displayed in the site
verbose_name_plural = verbose_name # Show plural names
def __str__(self):
return self.btitle # Define the display information of each data object
Registered routing
from django.urls import path
from django.conf.urls import url
from testdjango import views
# Import views Class view in view
urlpatterns = [
path('index/', views.IndexView.as_view()),
url(r'^books/$', views.BooksView.as_view()),
url(r'^books/(?P<pk>\d+)/$', views.BookView.as_view()),
]
Add view
class BooksView(View):
"""
Get all and save
"""
def get(self, request):
books = BookInfo.objects.all()
book_list = []
for book in books:
book_list.append(
{
'id':book.id,
'btitle': book.btitle,
'bpub_date': book.bpub_date,
'bcomment': book.bcomment
}
)
return JsonResponse(book_list, safe=False)
def post(self, request):
pass
class BookView(View):
"""
Get single and updated 、 Delete
"""
def get(self, request, pk):
pass
def put(self, request, pk):
pass
def delete(self, request, pk):
pass
visit :http://127.0.0.1:8000/projects/books/
2、 Save information interface
class BooksView(View):
"""
Get all and save interfaces
"""
def get(self, request):
books = BookInfo.objects.all()
book_list = []
for book in books:
book_list.append(
{
"id": book.id,
"btitle": book.btitle,
"bpub_date": book.bpub_date,
"bcomment": book.bcomment,
}
)
return JsonResponse(book_list, safe=False)
def post(self, request):
# 1、 Get request data
# 2、 Validate request data
# 3、 Save the data
# 4、 Return results
data = request.body.decode() #“{}”
data_dict = json.loads(data) # Turn it into a dictionary {}
btitle = data_dict.get("btitle")
bpub_date = data_dict.get("bpub_date")
bcomment = data_dict.get("bcomment")
if btitle is None or bpub_date is None:
return JsonResponse({'error': ' error message '}, status=400)
book = BookInfo.objects.create(btitle=btitle, bpub_date = bpub_date, bcomment=becomment)
return JsonResponse(
{
"id": book.id,
"btitle": book.btitle,
"bpub_date": book.bpub_date,
"bcomment": book.bcomment,
}
)
3、 Get single data 、 modify 、 Delete
class BookView(View):
"""
Get a single interface and modify 、 Delete interface
"""
def get(self, request, pk):
# 1、 Query a single data object , If you don't have this in the database id, Will report a mistake , So use try catch
try:
book = BookInfo.objects.get(id=pk)
except:
return JsonResponse({'error': ' error message '}, status=400)
return (
{
"id": book.id,
"btitle": book.btitle,
"bpub_date": book.bpub_date,
"bcomment": book.bcomment,
}
)
def put(self, request, pk):
# The same logic as saving , The front-end data is transmitted to the back-end , Just when saving data , Update data instead
# 1、 Get request data
# 2、 Validate request data
# 3、 Update data
# 4、 Return results
data = request.body.decode()
data_dict = json.loads(data)
btitle = data_dict.get('btitle')
bpub_date = data_dict.get('bpub_date')
bcomment = data_dict.get('becomment')
if btitle is None or bpub_date is None:
return JsonResponse({'error': ' Wrong data '}, status=400)
# Inquire about id Information about
try:
book = BookInfo.objects.get(id=pk)
except:
return JsonResponse({'error': ' error message '}, status=400)
# 3、 Update data , Assign the value obtained from the front end to the original field , Finally, use save preservation
book.btitle = btitle
book.bpub_date = bpub_date
book.becomment = becomment
book.save()
# 4、 Return the data
return JsonResponse(
{
"id": book.id,
"btitle": book.btitle,
"bpub_date": book.bpub_date,
"bcomment": book.bcomment,
}
)
def delete(self, request, pk):
try:
book = BookInfo.objects.get(id=pk)
except:
return JsonResponse({'error': ' error message '}, status=400)
# If you use book.delete It's physical deletion , So it can't be used , To use logical deletion
book.is_delete = True
book.save()
# Delete the data and return an empty
return JsonResponse({})
http://127.0.0.1:8000/projects/books/1/
Pay attention to when requesting interfaces , The last path needs to be added /