Django Python 对具有多个值的相同键进行 urlencode

Django Python urlencode same key with multiple values

如标题所示,我正在尝试使用 python

中的 Ordered Dict 进行 urlencode
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()))

以上代码的输出

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')])

如您所见,assigned_to_id 最后只有 2

我期待的是带有

的有序字典
OrderedDict([('assigned_to_id', '2'),('assigned_to_id', '1'), ('client_id', '1'), ('client_id', '2'),('page', '2')])

也许有更好的方法,我对 python

有点陌生

我的最终目标是 return 一个带有多个键的字典或任何可以在 urlencode 中使用的东西

urllib.parse.urlencode

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.

这是一个简单的例子:

from urllib import parse

print(parse.urlencode({"a": [1, 2], "b": 1}, doseq=True))
# "a=1&a=2&b=1"