问题:如何将Django QuerySet转换为字典列表?

如何将Django QuerySet转换为字典列表?我没有找到答案,所以我想知道我是否缺少每个人都使用的某种通用帮助函数。

How can I convert a Django QuerySet into a list of dicts? I haven’t found an answer to this so I’m wondering if I’m missing some sort of common helper function that everyone uses.


回答 0

使用.values()方法:

>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]

注意:结果是,QuerySet其行为基本上类似于列表,但实际上不是的实例list。使用list(Blog.objects.values(…))如果你真的需要的一个实例list

Use the .values() method:

>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]

Note: the result is a QuerySet which mostly behaves like a list, but isn’t actually an instance of list. Use list(Blog.objects.values(…)) if you really need an instance of list.


回答 1

方法将返回类型的结果,ValuesQuerySet这通常是大多数情况下所需的。

但是,如果您愿意,可以ValuesQuerySet使用Python列表理解功能将其转换为本地Python列表,如下例所示。

result = Blog.objects.values()             # return ValuesQuerySet object
list_result = [entry for entry in result]  # converts ValuesQuerySet into Python list
return list_result

我发现上面的帮助,如果你正在编写单元测试,并需要断言函数的预期收益值,实际的返回值匹配,在这种情况下,两个expected_resultactual_result必须是同一类型(例如字典)。

actual_result = some_function()
expected_result = {
    # dictionary content here ...
}
assert expected_result == actual_result

The method will return you a result of type ValuesQuerySet which is typically what you need in most cases.

But if you wish, you could turn ValuesQuerySet into a native Python list using Python list comprehension as illustrated in the example below.

result = Blog.objects.values()             # return ValuesQuerySet object
list_result = [entry for entry in result]  # converts ValuesQuerySet into Python list
return list_result

I find the above helps if you are writing unit tests and need to assert that the expected return value of a function matches the actual return value, in which case both expected_result and actual_result must be of the same type (e.g. dictionary).

actual_result = some_function()
expected_result = {
    # dictionary content here ...
}
assert expected_result == actual_result

回答 2

如果出于某种原因(例如JSON序列化)而需要本机数据类型,这是我的快速“ n”处理方式:

data = [{'id': blog.pk, 'name': blog.name} for blog in blogs]

如您所见,在列表中构建字典并不是真正的DRY,所以如果有人知道更好的方法…

If you need native data types for some reason (e.g. JSON serialization) this is my quick ‘n’ dirty way to do it:

data = [{'id': blog.pk, 'name': blog.name} for blog in blogs]

As you can see building the dict inside the list is not really DRY so if somebody knows a better way …


回答 3

您没有完全定义字典的外观,但很可能是您所指的QuerySet.values()。从官方的django文档中

返回一个ValuesQuerySetQuerySet子类,该子类在用作可迭代对象(而不是模型实例对象)时返回字典。

这些词典中的每一个都代表一个对象,其键对应于模型对象的属性名称。

You do not exactly define what the dictionaries should look like, but most likely you are referring to QuerySet.values(). From the official django documentation:

Returns a ValuesQuerySet — a QuerySet subclass that returns dictionaries when used as an iterable, rather than model-instance objects.

Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.


回答 4

输入类型到列表

    job_reports = JobReport.objects.filter(job_id=job_id, status=1).values('id', 'name')

    json.dumps(list(job_reports))

Type Cast to List

    job_reports = JobReport.objects.filter(job_id=job_id, status=1).values('id', 'name')

    json.dumps(list(job_reports))

回答 5

您可以values()在查询所依据的Django模型字段中使用dict上的方法,然后可以通过索引值轻松访问每个字段。

这样称呼它-

myList = dictOfSomeData.values()
itemNumberThree = myList[2] #If there's a value in that index off course...

You can use the values() method on the dict you got from the Django model field you make the queries on and then you can easily access each field by a index value.

Call it like this –

myList = dictOfSomeData.values()
itemNumberThree = myList[2] #If there's a value in that index off course...

回答 6

你需要DjangoJSONEncoderlist使您Querysetjson,参考:Python的JSON序列化一个小数对象

import json
from django.core.serializers.json import DjangoJSONEncoder


blog = Blog.objects.all().values()
json.dumps(list(blog), cls=DjangoJSONEncoder)

You need DjangoJSONEncoder and list to make your Queryset to json, ref: Python JSON serialize a Decimal object

import json
from django.core.serializers.json import DjangoJSONEncoder


blog = Blog.objects.all().values()
json.dumps(list(blog), cls=DjangoJSONEncoder)

回答 7

简单地说list(yourQuerySet)

Simply put list(yourQuerySet).


回答 8

您可以使用model_to_dict定义一个函数,如下所示:

def queryset_to_dict(qs,fields=None, exclude=None):
    my_array=[]
    for x in qs:
        my_array.append(model_to_dict(x,fields=fields,exclude=exclude))
    return my_array

You could define a function using model_to_dict as follows:

def queryset_to_dict(qs,fields=None, exclude=None):
    my_array=[]
    for x in qs:
        my_array.append(model_to_dict(x,fields=fields,exclude=exclude))
    return my_array

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