问题:如何将Django QueryDict更改为Python Dict?

假设我有以下QueryDict:

<QueryDict: {u'num': [0], u'var1': [u'value1', u'value2'], u'var2': [u'8']}>

我想要一本这样的字典,例如:

{'num': [0], 'var1':['value1', 'value2'], 'var2':['8']}

(我不在乎Unicode符号是否u继续存在。)

如果我queryDict.dict()按照django网站的建议进行操作,则会丢失属于的额外值var1,例如:

{'num': [0], 'var1':['value2'], 'var2':['8']}

我正在考虑这样做:

myDict = {}
for key in queryDict.iterkeys():
    myDict[key] = queryDict.getlist(key)

有没有更好的办法?

Let’s pretend I have the following QueryDict:

<QueryDict: {u'num': [0], u'var1': [u'value1', u'value2'], u'var2': [u'8']}>

I’d like to have a dictionary out of this, eg:

{'num': [0], 'var1':['value1', 'value2'], 'var2':['8']}

(I don’t care if the unicode symbol u stays or goes.)

If I do queryDict.dict(), as suggested by the django site, I lose the extra values belonging to var1, eg:

{'num': [0], 'var1':['value2'], 'var2':['8']}

I was thinking of doing this:

myDict = {}
for key in queryDict.iterkeys():
    myDict[key] = queryDict.getlist(key)

Is there a better way?


回答 0

这应该工作: myDict = dict(queryDict.iterlists())

This should work: myDict = dict(queryDict.iterlists())


回答 1


回答 2

这就是我最终使用的:

def qdict_to_dict(qdict):
    """Convert a Django QueryDict to a Python dict.

    Single-value fields are put in directly, and for multi-value fields, a list
    of all values is stored at the field's key.

    """
    return {k: v[0] if len(v) == 1 else v for k, v in qdict.lists()}

根据我的用法,这似乎为您提供了一个列表,您可以将其发送回例如表单构造函数。

编辑:也许这不是最好的方法。看来,如果您QueryDict出于某种疯狂的原因例如要写入文件,这是可行QueryDict.urlencode()的方法。要重建QueryDict您,只需要做QueryDict(urlencoded_data)

This is what I’ve ended up using:

def qdict_to_dict(qdict):
    """Convert a Django QueryDict to a Python dict.

    Single-value fields are put in directly, and for multi-value fields, a list
    of all values is stored at the field's key.

    """
    return {k: v[0] if len(v) == 1 else v for k, v in qdict.lists()}

From my usage this seems to get you a list you can send back to e.g. a form constructor.

EDIT: maybe this isn’t the best method. It seems if you want to e.g. write QueryDict to a file for whatever crazy reason, QueryDict.urlencode() is the way to go. To reconstruct the QueryDict you simply do QueryDict(urlencoded_data).


回答 3

from django.utils import six 
post_dict = dict(six.iterlists(request.POST))
from django.utils import six 
post_dict = dict(six.iterlists(request.POST))

回答 4

如果您不希望这些值作为数组,则可以执行以下操作:

# request = <QueryDict: {u'key': [u'123ABC']}>
dict(zip(request.GET.keys(), request.GET.values()))
{u'key': u"123ABC" }

# Only work for single item lists
# request = <QueryDict: {u'key': [u'123ABC',U 'CDEF']}>
dict(zip(request.GET.keys(), request.GET.values()))
{u'key': u"CDEF" } 

zip是一种功能强大的工具,请在此处详细了解它http://docs.python.org/2/library/functions.html#zip

If you do not want the values as Arrays you can do the following:

# request = <QueryDict: {u'key': [u'123ABC']}>
dict(zip(request.GET.keys(), request.GET.values()))
{u'key': u"123ABC" }

# Only work for single item lists
# request = <QueryDict: {u'key': [u'123ABC',U 'CDEF']}>
dict(zip(request.GET.keys(), request.GET.values()))
{u'key': u"CDEF" } 

zip is a powerful tool read more about it here http://docs.python.org/2/library/functions.html#zip


回答 5

我遇到了类似的问题,想将表单中的任意值保存为序列化值。

我的回答避免了显式地迭代字典内容: dict(querydict.iterlists())

为了检索起原始作用的类似于字典的值,可使用反函数QueryDict.setlist()来填充新QueryDict值。在这种情况下,我认为显式迭代是不可避免的。

我的辅助函数如下所示:

from django.http import QueryDict

def querydict_dict(querydict):
    """
    Converts a Django QueryDict value to a regular dictionary, preserving multiple items.
    """
    return dict(querydict.iterlists())

def dict_querydict(dict_):
    """
    Converts a value created by querydict_dict back into a Django QueryDict value.
    """
    q = QueryDict("", mutable=True)
    for k, v in dict_.iteritems():
        q.setlist(k, v)
    q._mutable = False
    return q

I ran into a similar problem, wanting to save arbitrary values from a form as serialized values.

My answer avoids explicitly iterating the dictionary contents: dict(querydict.iterlists())

In order to retrieve a dictionary-like value that functions as the original, an inverse function uses QueryDict.setlist() to populate a new QueryDict value. In this case, I don’t think the explicit iteration is avoidable.

My helper functions look like this:

from django.http import QueryDict

def querydict_dict(querydict):
    """
    Converts a Django QueryDict value to a regular dictionary, preserving multiple items.
    """
    return dict(querydict.iterlists())

def dict_querydict(dict_):
    """
    Converts a value created by querydict_dict back into a Django QueryDict value.
    """
    q = QueryDict("", mutable=True)
    for k, v in dict_.iteritems():
        q.setlist(k, v)
    q._mutable = False
    return q

回答 6

更新:

myDict = dict(queryDict._iterlists())

请注意:_的iterlists方法中的下划线queryDict。Django版本:1.5.1

Update:

myDict = dict(queryDict._iterlists())

Please Note : underscore _ in iterlists method of queryDict. Django version :1.5.1


回答 7

dict(request.POST) 返回带有数组包装值的怪异python字典。

{'start': ['2017-01-14T21:00'], 'stop': ['2017-01-14T22:00'], 'email': ['sandeep@sakethtech.com']}

作为{x:request.POST.get(x) for x in request.POST.keys()}返回预期输出的位置。

{'start': '2017-01-14T21:00', 'stop': '2017-01-14T22:00', 'email': 'sandeep@sakethtech.com'}

dict(request.POST) returns a weird python dictionary with array wrapped values.

{'start': ['2017-01-14T21:00'], 'stop': ['2017-01-14T22:00'], 'email': ['sandeep@sakethtech.com']}

where as {x:request.POST.get(x) for x in request.POST.keys()} returns expected output.

{'start': '2017-01-14T21:00', 'stop': '2017-01-14T22:00', 'email': 'sandeep@sakethtech.com'}

回答 8

只需添加

queryDict=dict(request.GET) 要么 queryDict=dict(QueryDict)

在您的视图中,数据将以python Dict的形式保存在querDict中。

just simply add

queryDict=dict(request.GET) or queryDict=dict(QueryDict)

In your view and data will be saved in querDict as python Dict.


回答 9

这就是我解决该问题的方法:

dict_ = {k: q.getlist(k) if len(q.getlist(k))>1 else v for k, v in q.items()}

This is how I solved that problem:

dict_ = {k: q.getlist(k) if len(q.getlist(k))>1 else v for k, v in q.items()}

回答 10

和我一样,您可能更熟悉Dict()python中的方法。但是,QueryDict()它也是易于使用的对象。例如,也许您想从中获取值request.GET QueryDict()

您可以这样操作:request.GET.__getitem__(<key>)

QueryDict()文档:https : //docs.djangoproject.com/en/2.0/ref/request-response/#django.http.QueryDict

Like me, you probably are more familiar with Dict() methods in python. However, the QueryDict() is also an easy object to use. For example, perhaps you wanted to get the value from the request.GET QueryDict().

You can do this like so: request.GET.__getitem__(<key>).

QueryDict() documentation: https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.QueryDict


回答 11

随着Django 2.2很少有干净的解决方案:

  1. QueryDict.dict()这是最简单的方法,但是会破坏QueryDict列表作为值,例如:
from django.http.request import QueryDict, MultiValueDict

query_dict = QueryDict('', mutable=True)
query_dict.update(MultiValueDict({'a': ['one', 'two']}))
query_dict.update({'b': 'three'})

for key, value in query_dict.dict().items():  # ---> query_dict.dict()
    print(key, value)

将输出

a two  # <--- missed 'one'
b three
  1. dict(QueryDict) 更好,因为它将使列表正确字典:
from django.http.request import QueryDict, MultiValueDict

query_dict = QueryDict('', mutable=True)
query_dict.update(MultiValueDict({'a': ['one', 'two']}))
query_dict.update({'b': 'three'})

for key, value in dict(query_dict).items():  # ---> dict(query_dict)
    print(key, value)

将输出

a ['one', 'two']
b ['three']

哪个是正确的。

With Django 2.2 there are few clean solutions:

  1. QueryDict.dict() is simplest but it will broke QueryDict with lists as values, e.g:
from django.http.request import QueryDict, MultiValueDict

query_dict = QueryDict('', mutable=True)
query_dict.update(MultiValueDict({'a': ['one', 'two']}))
query_dict.update({'b': 'three'})

for key, value in query_dict.dict().items():  # ---> query_dict.dict()
    print(key, value)

will output

a two  # <--- missed 'one'
b three
  1. dict(QueryDict) is better because it will make correct dictionary of lists:
from django.http.request import QueryDict, MultiValueDict

query_dict = QueryDict('', mutable=True)
query_dict.update(MultiValueDict({'a': ['one', 'two']}))
query_dict.update({'b': 'three'})

for key, value in dict(query_dict).items():  # ---> dict(query_dict)
    print(key, value)

will output

a ['one', 'two']
b ['three']

which is correct.


回答 12

我尝试了两者dict(request.POST)request.POST.dict()并意识到,如果您的list值中'var1':['value1', 'value2']嵌套了一些值request.POST,则late(request.POST.dict())仅使我可以访问嵌套列表中的最后一项,而前一个(dict(request.POST))则允许我访问嵌套列表中的所有项目。

我希望这可以帮助别人。

I tried out both dict(request.POST) and request.POST.dict() and realised that if you have list values for example 'var1':['value1', 'value2'] nested in your request.POST, the later(request.POST.dict()) only gave me access to the last item in a nested list while the former(dict(request.POST)) allowed me to access all items in a nested list.

I hope this helps someone.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。