Reputation: 399
As the title suggest I am trying to urlencode using Ordered Dict in python
def url_replace(request, field, value, direction=""):
dict_ = request.GET.copy()
if field == "order_by" and field in dict_.keys():
if dict_[field].startswith("-") and dict_[field].lstrip("-") == value:
dict_[field] = value
elif dict_[field].lstrip("-") == value:
dict_[field] = "-" + value
else:
dict_[field] = direction + value
else:
dict_[field] = direction + str(value)
print("UNORDERED___________________")
print(dict_)
print(super(MultiValueDict, dict_).items())
print("ORDERED_____________")
print(OrderedDict(super(MultiValueDict, dict_).items()))
print(OrderedDict(dict_.items()))
return urlencode(OrderedDict(dict_.items()))
The output for the above code
UNORDERED___________________
<QueryDict: {'assigned_to_id': ['1', '2'], 'client_id': ['2', '1'], 'page': ['2']}>
dict_items([('assigned_to_id', ['1', '2']), ('client_id', ['2', '1']), ('page', ['2'])])
OrderedDict([('assigned_to_id', '2'), ('client_id', '1'), ('page', '2')])
ORDERED_____________
OrderedDict([('assigned_to_id', ['1', '2']), ('client_id', ['2', '1']), ('page', ['2'])])
OrderedDict([('assigned_to_id', '2'), ('client_id', '1'), ('page', '2')])
As you can see the assigned_to_id has only 2
in the end .
What I am expecting is a ordered dict with
OrderedDict([('assigned_to_id', '2'),('assigned_to_id', '1'), ('client_id', '1'), ('client_id', '2'),('page', '2')])
Maybe there might be a better approach for this, I am a bit new to python
My final aim is to return a dict with multiple keys or anything that can be used in urlencode
Upvotes: 0
Views: 1365
Reputation: 11
Just using urlencode with doseq=True
Note: convert to a dict first, or it will not work
Example:
from urllib.parse import urlencode
@register.filter
def get_query_url(req_get, page_num=None):
copy = dict(req_get.lists())
if page_num is not None:
copy["page"] = page_num
result = urlencode(copy, doseq=True)
return f"?{result}"
See - https://docs.python.org/3/library/stdtypes.html#typesmapping
Upvotes: 0
Reputation: 1275
When a sequence of two-element tuples is used as the query argument, the first element of each tuple is a key and the second is a value. The value element in itself can be a sequence and in that case, if the optional parameter
doseq
evaluates to True, individual key=value pairs separated by '&' are generated for each element of the value sequence for the key. The order of parameters in the encoded string will match the order of parameter tuples in the sequence.
Here is a simple example:
from urllib import parse
print(parse.urlencode({"a": [1, 2], "b": 1}, doseq=True))
# "a=1&a=2&b=1"
Upvotes: 3