zoukankan      html  css  js  c++  java
  • ✍52 django向多张表添加数据

    每个优秀的人都有一段沉默的时光,那段时光是付出了很多努力,却得不到结果的日子,我们把它叫做扎根。

    原文链接 : https://blog.csdn.net/Return_Li/article/details/106242343

    同事遇到的多表数据写入和更新问题, 找到上面这篇文章, 记录下重点

    示例 :

    • models.py
    from django.db import models
    
    
    # 品牌
    class Brand(models.Model):
        name = models.CharField(max_length=20, verbose_name='名称')
        '''...其他字段省略....'''
    
        class Meta:
            db_table = 'tb_brand'
    
        def __str__(self):
            return self.name
    
    
    # 分类
    class Cate(models.Model):
        brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name='brand_cate', null=True, blank=True, verbose_name='外键关联')
        cate_name = models.CharField(max_length=100, verbose_name='分类名称')
        '''...其他字段省略....'''
    
        class Meta:
            db_table = 'tb_cate'
    
    
    # 商品
    class Goods(models.Model):
        cate = models.ForeignKey ( Cate, on_delete=models.CASCADE, related_name='cate_goods', null=True, blank=True,
                                    verbose_name='外键关联' )
        goods_name = models.CharField(max_length=50, verbose_name='商品名称')
        goods_size = models.CharField(max_length=50, verbose_name='商品规格')
        goods_count = models.CharField(max_length=100, verbose_name='商品数量')
        '''...其他字段省略....'''
    
        class Meta:
            db_table = 'tb_goods'
    
        def __str__(self):
            return self.goods_name
    
    • views.py
    from .serializers import *            
    from rest_framework.views import APIView    
    from rest_framework.response import Response  
    
    
    class GoodsListView(APIView):
        def post( self, request):
            '''添加数据集'''
            data = request.data
            print(data)
            brand = BrandSerializer(data=data)
            if brand.is_valid():
                brand.save()
                return Response ( {'code': 200,"message":'SUCCESS'} )
            else:
                print(brand.errors)
                return Response ( {'code': 400, "message":'ERROR'} )
    
        def put( self, request):
            '''修改数据集'''
            data = request.data
            brand_instance = Brand.objects.get(id=data['id'])
            brand = BrandSerializer(brand_instance,data)
            if brand.is_valid():
                brand.save()
                return Response ( {'code': 200,"message":'SUCCESS'} )
            else:
                print(brand.errors)
                return Response ( {'code': 400, "message":'ERROR'} )
    
    • serializer
    from goods.models import *
    from rest_framework import serializers
    
    class GoodsSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = Goods
            fields = ('id', 'goods_name', 'goods_count', 'goods_size')
    
    
    class CateSerializer(serializers.ModelSerializer):
    
        cate_goods = GoodsSerializer ( many=True )
    
        class Meta:
            model = Cate
            fields = ('id', 'cate_name', 'cate_goods')
    
    
    class BrandSerializer(serializers.ModelSerializer):
    
        brand_cate = CateSerializer ( many=True )
    
        class Meta:
            model = Brand
            fields = ('id', 'name', 'brand_cate')
    
        def create(self, validated_data):
            # pop 弹出 data 中的数据并保存
            brand_cates = validated_data.pop('brand_cate')
            # 并进行第一张表的添加
            brand = Brand.objects.create(**validated_data)
            # 遍历 弹出的第二张表的数据并添加第二章表, 且主键信息为单独添加
            for cate_data in brand_cates:
                cate_goods = cate_data.pop ( 'cate_goods' )
                cate = Cate.objects.create(brand=brand, **cate_data)
                # 第三张表数据添加
                for goods in cate_goods:
                    Goods.objects.create (cate=cate, **goods)
            return brand
    
        def update(self, instance, validated_data):
            # 获取当前json 数据中 外键表的数据
            brand_cate = validated_data.pop('brand_cate')
            # 通过 instance 实例 去获取它外键表的实例
            brand_cate_data = (instance.brand_cate).all()
            brand_cate_data = list(brand_cate_data)
            # 修改 当前实例表的数据
            instance.name = validated_data.get('name', instance.name)
            instance.save()
            # 遍历 pop弹出的 外键表要修改的数据
            for cate_data in brand_cate:
                # 继续弹出第三张表外键的数据
                goods_data = cate_data.pop ( 'cate_goods' )
                # 获取第一张外键的 实例
                cate_instance = brand_cate_data.pop(0)
                # 获取第三张表的实例
                cate_goods = list((cate_instance.cate_goods).all())
                # 更新 第一张外键表数据
                cate_instance.name = cate_data.get('cate_name', cate_instance.cate_name)
                cate_instance.save()
                # 遍历继续更新第三张表的数据
                for goods in goods_data:
                    goods_instance = cate_goods.pop(0)
                    goods_instance.goods_name = goods.get("goods_name",goods_instance.goods_name)
                    goods_instance.goods_count = goods.get("goods_count",goods_instance.goods_count)
                    goods_instance.goods_size = goods.get("goods_size",goods_instance.goods_size)
                    goods_instance.save()
            return instance
    
  • 相关阅读:
    组装query,query汇总,query字段
    POJ 1276, Cash Machine
    POJ 1129, Channel Allocation
    POJ 2531, Network Saboteur
    POJ 1837, Balance
    POJ 3278, Catch That Cow
    POJ 2676, Sudoku
    POJ 3126, Prime Path
    POJ 3414, Pots
    POJ 1426, Find The Multiple
  • 原文地址:https://www.cnblogs.com/songhaixing/p/15632917.html
Copyright © 2011-2022 走看看