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"})

批量删除:

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

相关推荐
Q_Q51100828518 分钟前
python+uniapp基于微信小程序的学院设备报修系统
spring boot·python·微信小程序·django·flask·uni-app
蓝色空白的博客32 分钟前
自动化测试脚本-->集成测试部署思路整理(1)
python·集成测试
Blossom.1181 小时前
把AI“绣”进丝绸:生成式刺绣神经网络让古装自带摄像头
人工智能·pytorch·python·深度学习·神经网络·机器学习·fpga开发
m0_736927041 小时前
想抓PostgreSQL里的慢SQL?pg_stat_statements基础黑匣子和pg_stat_monitor时间窗,谁能帮你更准揪出性能小偷?
java·数据库·sql·postgresql
lang201509281 小时前
MySQL 8.0.29 及以上版本中 SSL/TLS 会话复用(Session Reuse)
数据库·mysql
星星也在雾里1 小时前
【管理多版本Python环境】Anaconda安装及使用
python·anaconda
望获linux1 小时前
【实时Linux实战系列】使用 u-trace 或 a-trace 进行用户态应用剖析
java·linux·前端·网络·数据库·elasticsearch·操作系统
用户3721574261351 小时前
使用 Python 将 CSV 文件转换为 PDF 的实践指南
python
大佬,救命!!!1 小时前
算法实现迭代2_堆排序
数据结构·python·算法·学习笔记·堆排序
清和与九2 小时前
binLog、redoLog和undoLog的区别
数据库·oracle