DRF学习第二课,实战

1,models模型

class BookInfo(models.Model):
    title=models.CharField(verbose_name="图书名称",max_length=32)
    pub_date=models.DateField(verbose_name="发布日期")
    read=models.IntegerField(default=0,verbose_name="阅读量")
    comment=models.IntegerField(verbose_name="评论量",default=0)
    is_delete=models.BooleanField(verbose_name="是否删除",default=False)
    class Meta:
        verbose_name=verbose_name_plural="图书"
    
    def __str__(self):
        return self.title
class HeroInfo(models.Model):
    gender_choices=(
        (0,'male'),
        (1,'female'),
    )
    name=models.CharField(max_length=32,verbose_name="名称")
    gender=models.SmallIntegerField(choices=gender_choices,default=0,verbose_name="性别")
    des=models.CharField(verbose_name="描述信息",max_length=255,null=True,blank=True)
    book=models.ForeignKey(BookInfo,on_delete=models.CASCADE,verbose_name="图书")
    is_delete=models.BooleanField(verbose_name="是否删除",default=False)
    class Meta:
        verbose_name=verbose_name_plural="英雄"
    
    def __str__(self):
        return self.name

2,urls.py的URL设置

    path('books',views.BooskView.as_view()),
    re_path('books/(?P<pk>\d+)',views.BookView.as_view()),

3,views.py使用

from app01 import models
from django.http import JsonResponse
# Create your views here.
from django.views import View
import json


class BooskView(View):
    """
    获取所有和保存
    #可关联英雄的数据,也就是反向查询
    heroinf_set=serializers.PrimaryRelatedField(read_only=True,many=True)
    """

    def get(self, request):
        # 1,查询所有图书对象2,返回图书数据[{},{}]

        books = models.BookInfo.objects.all()
        book_list = []
        for book in books:
            book_list.append(
                {'id': book.id,
                 'title': book.title,
                 'read': book.read,
                 'comment': book.comment,
                 'pub_date': book.pub_date,
                 }
            )
        return JsonResponse(book_list, safe=False)

    def post(self, request):
        # 1,获取前端数据 2,验证数据 3,保存数据 4,返回结果
        data = request.body.decode()
        data_dic = json.loads(data)
        title = data_dic.get('title')
        pub_date = data_dic.get('pub_date')
        if pub_date is None or title is None:
            return JsonResponse({'error': "书名或日期不能为空"}, status=400)
        book = models.BookInfo.objects.create(title=title, pub_date=pub_date)
        return JsonResponse(
            {
                'id': book.id,
                'title': book.title,
                'read': book.read,
                'comment': book.comment,
                'pub_date': book.pub_date,
            }
        )


class BookView(View):
    """
    获取单条
    """

    def get(self, request, pk):
        try:
            book=models.BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': "ID不存在"}, status=400)
        return JsonResponse(
            {
                'id': book.id,
                'title': book.title,
                'read': book.read,
                'comment': book.comment,
                'pub_date': book.pub_date,
            }
        ) 
    def put(self, request, pk):
         # 1,获取前端数据 
        data = request.body.decode()
        data_dic = json.loads(data)
        title = data_dic.get('title')
        pub_date = data_dic.get('pub_date')
        if pub_date is None or title is None:
            return JsonResponse({'error': "书名或日期不能为空"}, status=400)
        #查询数据是否存在
        try:
            book=models.BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': "书名或日期不能为空"}, status=400)
        #获取数据并保存
        book.title=title
        book.pub_date=pub_date
        book.save()#必须有这个,否则不能成功更新
        
        return JsonResponse(
            {
                'id': book.id,
                'title': book.title,
                'read': book.read,
                'comment': book.comment,
                'pub_date': book.pub_date,
            }
        )

    def delete(self, request, pk):
        try:
            book=models.BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error':'错误信息'},status=400)
        #此处是物理删除,正常一般采用逻辑删除。 is_delete=True  book.save()
        book.delete()
        return JsonResponse({})

 

posted @ 2023-05-27 21:18  super_ip  阅读(17)  评论(0编辑  收藏  举报