TIL#76 Django ORM & MySQL


Django ORM & MySQL


自分がやった比較結果を記録する📝
<n行目に出力>
SELECT name,price FROM Products LIMIT 5;
Product.objects.all()[:5]
SELECT name,price FROM products LIMIT 5 OFFSET 5;
-> 5개 건너뛰고 6번째부터 출력됨
Product.objects.all()[5:10]
<条件付き出力>
  • idが10の製品出力
  • select name,price from products where id=10;
    Product.objects.filter(id=10)
  • 金額が10000元から13000元の間の製品出力
  • .
    select name,price from products where price between 10000 and 13000;
    Product.objects.filter(price__range=(10000, 13000))

  • 文字列の検索
    binaryで大文字と小文字を区別します.likeの後ろに検索文字列を書くと、%は他の文字とみなされやすくなります.%new newで終わる文字列、%new% newを含む文字列、new% newで始まる文字列を検索します.
    iと入力した場合、大文字と小文字は区別されません.
    条件キーリファレンスリンク

  • 出力idが10,20の商品
  • select id, price, name from products where id in (10, 20);
    Product.objects.filter(id__in=[10,20])
  • idが100未満、金額が10000元未満の商品出力
  • .
    select name, price from products where id<100 and price <10000;
    Product.objects.filter(id__lt=100, price__lt=10000)
    Product.objects.filter(Q(id__lt=100) & Q(price__lt=10000))
  • id出力110以上5000元未満の商品
  • select name,price from products where id>110 or price<5000;
    Product.objects.filter(Q(id__gt=110) | Q(price__lt=5000))
  • 出力「ダノ」のない商品
  • select name, price from products where not name like '%다노%';
    Product.objects.exclude(name__contains='다노')
    価格順
  • (低から低)
  • select name,price from products order by price;
    Product.objects.order_by('price')
  • 価格ソート(高価格から)
  • select name,price from products order by price desc;
    Product.objects.order_by('-price')
  • 商品の最低価格
  • select min(price) from products;
    Product.objects.all().aggregate(Min('price'))
  • 商品の最大値
  • を獲得
    select max(price) from products;
    Product.objects.all().aggregate(Max('price'))
    ->同様に平均(AVG)、および(SUM)でもよい.
  • 商品総数
  • を獲得
    select count(*) from products;
    Product.objects.count()
  • などの割引率を組み合わせて、数個出力して、今はもっと理解する必要があります!
  • select discount_rate, count(*) as count from products group by discount_rate;
    Product.objects.values('discount_rate').annotate(count=Count('discount_rate'))
  • 以上の条件でcountが1より大きい
  • のみが出力.
    select discount_rate, count('discount_rate') as count from products group by discount_rate having count > 1;
    Product.objects.values('discount_rate').annotate(count=Count('discount_rate')).filter(count__gt=1)