序列化元件的使用及介面設計

Bound_w發表於2018-12-06

通過序列化的元件進行介面設計

    --GET :  127.0.0.1:8000/books/ # 獲取所有資料,返回值: [{}, {}]

    GET :  127.0.0.1:8000/books/{id} # 獲取一條資料,返回值:{}
    POST :  127.0.0.1:8000/books/ # 新增一條資料,返回值:{}
    PUT :  127.0.0.1:8000/books/{id} # 修改資料,返回值:{}
    DELETE:      127.0.0.1:8000/books/{id} # 刪除資料,返回空

執行流程:

modes.py

from django.db import models

# Create your models here.

class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()

    def __str__(self):
        return self.name


class Publish(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
    email = models.EmailField()

    def __str__(self):
        return self.name


class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    # 外來鍵欄位
    publish = models.ForeignKey(to="Publish", related_name="book", related_query_name="book_query", on_delete=models.CASCADE)
    # 多對多欄位
    authors = models.ManyToManyField(to="Author")

  1.匯入模組:          from rest_framwork  import  serializes

  2.建立一個序列化的類     class BookSerializer(serializers.Serializer): 

class BookSerializer(serializers.Serializer):
    # nid = serializers.CharField(max_length=32)
    title = serializers.CharField(max_length=128)
    price = serializers.DecimalField(max_digits=5, decimal_places=2)
    # 外來鍵欄位, 顯示__str__方法的返回值
    publish = serializers.CharField(max_length=32, source="publish.city")
    # authors = serializers.CharField(max_length=32) # book_obj.authors.all()

    # 多對多欄位需要自己手動獲取資料,SerializerMethodField()
    authors_list = serializers.SerializerMethodField()

    def get_authors_list(self, book_obj):
        author_list = list()

        for author in book_obj.authors.all():
            author_list.append(author.name)

        return author_list

    def create(self, book_obj):
        return book_obj

檢視:

1.匯入模序列化類的模組,和APIView模組
  from.app_serializers import BookSerializer
  from rest_framework.views import APIView
2.建立類(攜帶引數和不攜帶引數)
  class BookView(APIView)
    def get(self,request);
#獲取request
      origin_data=Book.objects.all()
#開始序列化
      serialized_data=BookSerializer(origin_data,many=True)
      return Response(serialized_data.data)
    
    def post(self,request):
      verified_data=BookSerializer(data=request.data)
      if verified.is_valid():
        book=verified_data.save()
        authors=Author.objects.filter(nid__in=request.data['authors'])
        book.authors.add(*authors)
        return Response(verifiled_data.data)
      else:
        return Response(verifiled_data.errors)

class BookFilterView(APIView):
  def get(self,request,nid)
    book_obj=Book.objects.get(pk=nid)
    serialized_data=BookSerialzer(book_obj,many=False)
    return Response(serialized_data.data)
  
  def put(self,request,nid):
    book_obj=Book.objects.get(pk=nid)
    verfiled_data=BookSerializer(data=request.data,instabce=book_oobj)
    if verfiles_data.is_valid():
      verfiled_data.save()
      return Response(verfiled_data.data)
    else:
      retuen Response(vefriled_data.errors)


  def delete(self,request,nid):
    book_obj=Book.objects.get(pk=nid).delete()
      return Response()

 

相關文章