21
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

django の QueryDict に関する覚書

Last updated at Posted at 2014-07-13

request.POST とかで使われているやつです。 dict との挙動の違いを確認する必要があったのでメモ。

特長は、

  • クエリストリングを渡してインスタンスを作る
  • Immutable (でも mutable=True を渡せる)
  • 値をリストで保持している (MultiValueDict を継承している)
>>> from django.http import QueryDict
>>> qd = QueryDict('spam=1&egg=2')

# get で取得すると文字列が返る
>>> qd.get('spam')
u'1'

# getlist で取得するとリストが返る
>>> qd.getlist('spam')
[u'1']

# クエリストリングに戻す
>>> qd.urlencode()
u'egg=2&spam=1'

# 値をセットしてみる
>>> qd['spam'] = 100
AttributeError: This QueryDict instance is immutable

# mutable=True で QueryDict を作る
>>> qd2 = QueryDict('spam=1&egg=2', mutable=True)                                                                                                                                 
>>> qd2.get('spam')
u'1'
>>> qd2['spam'] = 100
>>> qd2.get('spam')
100

# dict に変換してみる
>>> d = dict(qd)
>>> d.get('spam')
[u'1']
21
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?