why django multivaluedict get returns last element

4.5k Views Asked by At

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 ?

1

There are 1 best solutions below

2
On

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.