1. 程式人生 > 實用技巧 >django restframework 多對多的批量修改,基於邏輯刪

django restframework 多對多的批量修改,基於邏輯刪

模型:

class LogisticQuerySet(QuerySet):
    def delete(self):
        self.update(is_delete=True)

class BookManager(models.Manager):
    _queryset_class = LogisticQuerySet
    def get_queryset(self):
        """
        # todo 重寫查詢類 過濾is_delete=False
        Return a new QuerySet object. Subclasses can override this method to
        customize the behavior of the Manager.
        """
        return super().get_queryset().filter(is_delete=False)



class Book(models.Model):
    book_name=models.CharField(max_length=40)
    price=models.DecimalField(max_digits=4,decimal_places=2)
    publish=models.ForeignKey(to="Publish",on_delete=models.CASCADE,related_name="publish")
    author=models.ManyToManyField(to="Author",related_name="author")
    is_delete=models.BooleanField(default=False)


    class Meta:
        db_table="tbl_book"

    objects = BookManager()
    # def __str__(self):
    #     return self.book_name
    def delete(self, using=None, keep_parents=False):
        self.is_delete=True
        self.save()



class Publish(models.Model):
    publish_name=models.CharField(max_length=20)
    address=models.CharField(max_length=30)
    is_delete = models.BooleanField(default=False)
    class Meta:
        db_table="tbl_publish"
    # def __str__(self):
    #     return self.publish_name

    def delete(self, using=None, keep_parents=False):
        self.is_delete=True
        self.save()

class Author(models.Model):
    sex_choices=[(0,"男"),(1,"女")]
    name=models.CharField(max_length=20,unique=True)
    phone=models.BigIntegerField()
    sex=models.IntegerField(choices=sex_choices)
    is_delete = models.BooleanField(default=False)
    class Meta:
        db_table="tbl_author"

    # def __str__(self):
    #     return self.name
    def delete(self, using=None, keep_parents=False):
        self.is_delete=True
        self.save()

  

以上是模型刪除物件刪除重寫和查詢集合的刪除重寫,

序列化器:

class SerBookList(serializers.ListSerializer):

    def update(self, queryset_list, validated_data_list):
        queryset=[]
        for index, validated_data in enumerate(validated_data_list):
            inst=self.child.update(queryset_list[index], validated_data)
            queryset.append(inst)
        return queryset

    def validate(self, attrs):
        if not attrs:
            raise serializers.ValidationError("陣列不能為空")
        return attrs

class SerBook(serializers.ModelSerializer):
    """  add(1) add(1,2), set(list_object), remove(1), remove(1,2) or remove(*[1,2])"""

    class Meta:
        model=Book
        fields="__all__"
        list_serializer_class = SerBookList



class  SerPublish(serializers.ModelSerializer):
    class Meta:
        model = Publish
        fields = "__all__"

class  SerAuthor(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = "__all__"

  

檢視:

class BookView(APIView):
    """https://www.cnblogs.com/zx125/articles/11985347.html"""


    def get(self,request,*args,**kwargs):

        pk= kwargs.get("id")
        if pk :
            inst = Book.objects.filter(id=kwargs.get("id")).first()
            if inst:
                ser = SerBook(instance=inst, many=False)
                return Response(data=ser.data, status=200)
            else:
                return Response(data={"msg": "not found", "data": []}, status=200)
        else:
            inst = Book.objects.all()
            ser = SerBook(instance=inst, many=True)
            return Response(data=ser.data, status=200)


    def post(self,request,*args,**kwargs):
        data=request.data
        many=False
        if isinstance(data,list):
          many=True
        ser = SerBook(data=data, many=many)
        if ser.is_valid():
            ser.save()
            return Response(data=ser.data, status=status.HTTP_200_OK)
        else:
            return Response(data=ser.errors, status=status.HTTP_404_NOT_FOUND)


    def put(self,request,*args,**kwargs):
         data=request.data
         pk=kwargs.get("id")
         if pk and isinstance(data,dict):
            inst=Book.objects.filter(id=pk).first()
            if inst:
                ser = SerBook(instance=inst, many=False,data=data
                              )
                if ser.is_valid():
                    ser.save()
                return Response(data=ser.data, status=200)
            else:
                return Response(data={"msg":"not found 404","data":[],"code":200},status=200)
         elif isinstance(data,list):
            try:
                ids=[inst.pop("id") for inst in data]
                queryset=Book.objects.filter(id__in=ids)
                serializer=SerBook(instance=queryset,many=True,data=data)
                if serializer.is_valid():
                    serializer.save()
                    datas = serializer.data
                else:
                    datas = serializer.errors
                return Response(data=datas, status=200)
            except KeyError as e :
                return  Response(data={"msg":"id not found in dict item of list  "})
    def delete(self,request,*args,**kwargs):
        pk= kwargs.get("id")
        data=request.data
        if pk:
            inst=Book.objects.filter(id=pk).first()
            if inst:
                inst.delete()
                return Response(data={"code":200,"msg":"刪除ok"})
            else: return Response(data={"code":404,"msg":"刪除失敗,不存在!"})
        else:
            ids=data.get("ids")
            if isinstance(ids,list):
                objs=Book.objects.filter(id__in=ids)
                objs.delete()
                return Response(data={"code":200,"msg":"刪除ok"})