クエリ文字列
CoddyのDjangoジャーニー「Djangoの基礎」セクションの一部。レッスン 8/23。
注文ページには常に medium と表示されます。顧客が選んだサイズは、疑問符の後にアドレスの中で渡せます: /order/?size=large。
この部分はクエリ文字列です: name=valueのペアが&で結合されています。これはルートの一部ではないため、path("search/", ...)は/search/?q=cakeにも一致します。ビューはrequest.GETからペアを読み取ります。これは辞書のように機能します:
def search(request):
word = request.GET.get("q", "")
if len(word) > 30:
word = word[:30]
return HttpResponse(f"Results for {word}").get()は、名前が存在しない場合の既定値を受け取ります。一方、request.GET["q"]を使うとエラーになります。すべての値はテキストとして渡され、?の後には誰でも何でも入力できるため、値を使う前に確認してください。チャレンジ
簡単/order/でクエリ文字列からサイズを読み取るようにします。
?size=largeの場合はYou ordered a large coffee.と表示されます。smallとmediumの場合も同様です。- サイズが指定されていない場合、またはカフェで販売していない
hugeのようなサイズが指定された場合は、ミディアムコーヒーを注文します。
Runを押すと、プレビューで/order/?size=largeが開きます。
自分で試してみよう
from django.http import HttpResponse
DRINKS = {
"espresso": {"name": "Espresso", "price": 2.5, "description": "A short, strong shot of coffee."},
"latte": {"name": "Latte", "price": 3.5, "description": "Espresso with lots of steamed milk."},
"flat-white": {"name": "Flat White", "price": 3.75, "description": "Espresso with a thin layer of silky milk."},
"hot-chocolate": {"name": "Hot Chocolate", "price": 3, "description": "Dark chocolate melted into warm milk."},
}
def home(request):
return HttpResponse("<h1>Welcome to Corner Café</h1><p>Fresh coffee and cake every day.</p>")
def about(request):
return HttpResponse("Corner Café opened in 2026.")
def hours(request):
return HttpResponse("Open every day from 8:00 to 18:00.")
def contact(request):
return HttpResponse("Write to us at hello@cornercafe.example.")
def table(request, number):
return HttpResponse(f"<h1>Table {number}</h1>")
def drink(request, slug):
item = DRINKS[slug]
return HttpResponse(f"<h1>{item['name']}</h1><p>{item['description']}</p>")
def order(request):
size = "medium"
return HttpResponse(f"You ordered a {size} coffee.")
Djangoの基礎のすべてのレッスン
自分で練習してみよう: Djangoプレイグラウンド