django restframework 多对多模型 —— python

模型 图书和作者是多对多关系

python 复制代码
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")



    class Meta:

        db_table="tbl_book"



    # def __str__(self):

    #     return self.book_name



class Publish(models.Model):

    publish_name=models.CharField(max_length=20)

    address=models.CharField(max_length=30)



    class Meta:

        db_table="tbl_publish"

    # def __str__(self):

    #     return self.publish_name



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)



    class Meta:

        db_table="tbl_author"



    # def __str__(self):

    #     return self.name

序列化器:

python 复制代码
class SerBook(serializers.ModelSerializer):

    """  add(1) add(1,2), set(list_object), remove(1), remove(1,2) or remove(*[1,2])"""

    #publish = serializers.PrimaryKeyRelatedField(queryset=Publish.objects.all())

    #author = serializers.PrimaryKeyRelatedField(allow_empty=False, many=True, queryset=Author.objects.all())

    class Meta:

        model=Book

        fields="__all__"





class  SerPublish(serializers.ModelSerializer):

    class Meta:

        model = Publish

        fields = "__all__"



class  SerAuthor(serializers.ModelSerializer):

    class Meta:

        model = Author

        fields = "__all__"

视图以图书为例:

python 复制代码
class BookView(APIView):





    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 :

            inst=Book.objects.filter(id=pk).first()

            print(Book.objects.filter(id=pk).values().first(),"xxxx")

            if inst:

                ser = SerBook(instance=inst, many=False,data=data

                              )

                if ser.is_valid():

                    ser.save()

                return Response(data=ser.data, status=200)<br>  

序列化器结构:

postman测试:

创建单个图书:

PUT 修改图书根据图书book id:

多对多删除:

python 复制代码
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"})

批量删除:

本次分享到此结束,感谢大家的阅读!

相关推荐
ZXF_H1 小时前
pip安装github上的开源软件包
git·python·github·pip
没事别学JAVA1 小时前
使用Python编写Windows系统服务管理脚本,主要用于管理mysql、postgresql等服务
windows·python
yivifu2 小时前
用python将一个扫描pdf文件改成二值图片组成的pdf文件
python·pdf·numpy·pillow·pymupdf
Eric.Lee20213 小时前
数据集-目标检测系列- 装甲车 检测数据集 armored_vehicles >> DataBall
python·算法·yolo·目标检测·装甲车检测
Eric.Lee20213 小时前
数据集-目标检测系列- 牵牛花 检测数据集 morning_glory >> DataBall
人工智能·python·yolo·目标检测·计算机视觉·牵牛花检测
tianyunlinger4 小时前
rope编码代码分享
pytorch·python·深度学习
java_heartLake6 小时前
PostgreSQL数据库参数调优实践
数据库·postgresql·调优
IT古董6 小时前
【机器学习】如何使用Python的Scikit-learn库实现机器学习模型,并对数据进行预处理和特征缩放以提高模型性能?
python·机器学习·scikit-learn
xnuscd7 小时前
Milvus概念
数据库·学习·mysql
Want5957 小时前
Python绘制太极八卦
开发语言·python