1

I have used Django MultiValueDict many times and all the times either I use the entire list stored with a key or I want to use the first value from the list. A common use case is use it as form initial data.

My problem is that by default Django MultiValueDict's get method returns last element.

Do I have to override getitem of MultiValueDict or is there any better alternative ?

afsantos
  • 5,178
  • 4
  • 30
  • 54
Rajesh Kaushik
  • 1,471
  • 1
  • 11
  • 16

1 Answers1

0

You can use:

mv_dict.getlist()[index]

Where index is the index of the element you want in the list. For example 0 to get the first element.

Check https://github.com/django/django/blob/master/django/utils/datastructures.py#L285

But certainly if for some reason you always want to return the first element of the list, subclassing MultiValueDict sounds reasonable. It depends on your use case.

dukebody
  • 7,025
  • 3
  • 36
  • 61
  • That's right. But again I have to handle ListIndex error. Actually I am curious about why last element and not first? What is the common use case for last element? – Rajesh Kaushik Oct 29 '14 at 11:37
  • Answer in source code: _This class exists to solve the irritating problem raised by cgi.parse_qs, which returns a list for every key, even though most Web forms submit single name-value pairs._ – dukebody Oct 29 '14 at 12:27