1. 程式人生 > 實用技巧 >ORM基本操作

ORM基本操作

1、建立單表模型類

class Goods(models.Model):
    goods_name = models.CharField(max_length=32)
    goods_price = models.DecimalField(max_digits=9,decimal_places=2)
    goods_num = models.IntegerField()

    class Meta:
        db_table = 'tb_goods'

2、ORM基本操作

   class ORMView(APIView):
    def get(self,request):
        # 單一查詢,如果結果不存在報錯
        goodsobj = Goods.objects.get(goods_price=6.66)
        obj = GoodsSerializers(goodsobj)
        return Response(obj.data)
   
   # # 查詢不包含id=3的資料
    # goodsobj = Goods.objects.exclude(id=3)
    # obj = GoodsSerializers(goodsobj, many=True)
    # return Response(obj.data)
        # # 查詢結果的數量
# goodsobj = Goods.objects.all().count()
# return Response(goodsobj)
 # #   聚合函式  使用aggregate()過濾器呼叫聚合函式。聚合函式包括:Avg 平均,Count 數量,Max 最大,Min 最小,Sum 求和
     # goodsobj = Goods.objects.aggregate(Sum('goods_num'))
    # print(goodsobj)
    # # obj = GoodsSerializers(goodsobj, many=True)
    # return Response({'data':''})
  # #   比較查詢  欄位名__lt:小於    欄位名__lte:小於等於
    # goodsobj = Goods.objects.filter(id__lt=4)
    # obj = GoodsSerializers(goodsobj, many=True)
    # return Response(obj.data)
 # #   比較查詢  欄位名__gt:大於    欄位名__gte:大於等於
    # goodsobj = Goods.objects.filter(id__gte=2)
    # obj = GoodsSerializers(goodsobj, many=True)
    # return Response(obj.data)
  # #   空查詢  欄位名__isnull
# goodsobj = Goods.objects.filter(goods_name__isnull=False)
# obj = GoodsSerializers(goodsobj, many=True)
# return Response(obj.data)
 # #   模糊查詢 欄位名__endswith 以 莓 結尾的資料
    # goodsobj = Goods.objects.filter(goods_name__endswith='莓')
    # obj = GoodsSerializers(goodsobj, many=True)
    # return Response(obj.data)
      # #   模糊查詢 欄位名__tartswith 以 蘋 開頭的資料    # goodsobj = Goods.objects.filter(goods_name__startswith='蘋')    # obj = GoodsSerializers(goodsobj,many=True)    # return Response(obj.data)​    # #   模糊查詢 欄位名__contains 包含 果 的的資料    # goodsobj = Goods.objects.filter(goods_name__contains='果')    # obj = GoodsSerializers(goodsobj,many=True)    # return Response(obj.data)
  # # 範圍查詢:  in  只查詢列表中的具體值
    # goodsobj = Goods.objects.filter(goods_price__in=[12,25,6.66]).all()
    # obj = GoodsSerializers(goodsobj,many=True)
    # return Response(obj.data)

    # # 範圍查詢:  range 1~20之間
    # goodsobj = Goods.objects.filter(goods_price__range=[1,20]).all()
    # obj = GoodsSerializers(goodsobj,many=True)
    # return Response(obj.data)
  #    排序查詢:  order_by 降序只需在欄位名前加上 “ - ”
        goodsobj = Goods.objects.all().order_by('-goods_num')
        obj = GoodsSerializers(goodsobj, many=True)
        return Response(obj.data)

        #    F方法:比較兩個欄位物件之間的關係用F物件,F方法可以進行簡單運算 
        #    查詢價格 大於等於 庫存的物件
        goodsobj = Goods.objects.filter(goods_price__gte=F('goods_num'))
        obj = GoodsSerializers(goodsobj, many=True)
        return Response(obj.data)
        
        #    Q方法:對物件進行復雜查詢,並支援&(and),|(or),~(not)操作符
        #    查詢價格大於等於15的資料 或庫存大於等於10的資料
        goodsobj = Goods.objects.filter(Q(goods_price__gte=15) | Q(goods_num__gte=10))
        obj = GoodsSerializers(goodsobj, many=True)
        return Response(obj.data)

3、建立一對多、多對多模型類

# 電影
class Movie(models.Model):
    movie_name = models.CharField(max_length=32)
    class Meta:
        db_table = 'tb_movie'


# 角色
class Role(models.Model):
    role_name = models.CharField(max_length=32)
    role_price = models.DecimalField(max_digits=9, decimal_places=2)
    role_desc = models.CharField(max_length=32)

    class Meta:
        db_table = 'tb_role'


# 演員
class Actor(models.Model):
    name = models.CharField(max_length=32)
    address = models.CharField(max_length=32, null=True, blank=True)
    age = models.IntegerField(null=True,blank=True)
    phone = models.CharField(max_length=32, null=True, blank=True)
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
    role = models.ManyToManyField(Role)

    class Meta:
        db_table = 'tb_actor'
  • 一對多正、反查詢
   # #   正向查詢  物件.模型名.欄位
    # actorobj = Actor.objects.get(id=1)
    # movieo = actorobj.movie.movie_name
    # print(movieo)
    # return Response('ok')

    #   反向查詢  物件.模型名_set
    # movieobj = Movie.objects.get(id=1)
    # actorobj = movieobj.actor_set.all()
    # obj = ActorSerializers(actorobj,many=True)
    # print(obj.data)
    # return Response(obj.data)

4、多對多表操作

class ORMview2(APIView):
    def post(self,request):
        # # 多對多新增
        # # 方法一:在建立manytomany的models裡新增資料,(一條,一個物件)
        # actor = Actor.objects.get(id=5)
        # role = Role.objects.get(id=5)
        #
        # data = actor.role.add(role)
        # print(data)
        # return Response('ok')


# 方法二:在未建立manytomany的models裡新增資料,(一條,一個物件)
    actor = Actor.objects.filter(name='張譯')
    role = Role.objects.get(id=5)

    data = role.actor_set.add(*actor)
    print(data)
    return Response('ok2')

5、父子元件的呼叫

import匯入子元件
components註冊子元件
註冊的子元件當作標籤來使用

  • 子元件
<template>​  <div>​      <p>今天心情真美麗</p>   </div>​</template>
  • 父元件

    <template>
    <div>
     <zi></zi>     <!-- 子元件當標籤使用-->
    
     </div>
    
    </template>
    
    <script>
    
    import zi from "./zi";     //匯入子元件
    
    export default {
    
     data() {
       return { 
    
        };
    
       },
    //註冊子元件
       components: {     
    
        zi
    
       },
    
    }
    </script>
    
  • 父元件給子元件傳參

    父元件裡的子標籤裡寫上要傳遞的資料(:子元件的引數名字=父元件的引數名字)
    在子元件裡註冊引數(props)
    使用父元件傳過來的引數

<template>
  <div>
    <zi :str='str'></zi><br>      
    <br>
    <button @click="change_zi()">修改子元件</button>
  </div>
</template>

<script>
import zi from "./zi";
export default {
  data() {
    return {
        str:'',
     
    };
  },

  components: {
    zi
  },

  methods:{
      change_zi(){
          this.str='今天的你真可愛!'
      },
  }
};
</script>

//子元件獲取
<template>
  <div>
      <p>今天心情真美麗</p>
      {{str}}
  </div>
</template>

<script>
export default {
    props:['str'],
    data(){
        return{

        }

    },
  }
</script>
  • 子元件給父元件傳參

    子元件裡先用特定的方法來把這個資料傳遞給父元件(this.$emit(‘方法的名字’,要傳遞的資料))
    父元件的子標籤裡來接收資料(@子元件的方法=父元件的方法)
    methods裡接收傳過來的val並賦值

<template>
  <div>
      <p>今天心情真美麗</p>
      <button @click="change">修改父元件</button>
  </div>
</template>

<script>
export default {
    data(){
        return{

        }

    },
    methods:{
        change(){
            this.$emit('change_fu','真好!nice!')
        }
        
    }

}
</script>


//父元件獲取
<template>
  <div>
    <zi @change_fu=get_zi></zi><br>
    {{data}}
  </div>
</template>

<script>
import zi from "./zi";
export default {
  data() {
    return {
        data:''
    };
  },

  components: {
    zi
  },

  methods:{
      get_zi(val){
          this.data=val
      }
  }
};
</script>