How do I convert a Django QuerySet into list of dicts?

前端 未结 9 553
臣服心动
臣服心动 2020-12-02 07:28

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 every

相关标签:
9条回答
  • 2020-12-02 07:49

    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.

    0 讨论(0)
  • 2020-12-02 07:50

    Type Cast to List

        job_reports = JobReport.objects.filter(job_id=job_id, status=1).values('id', 'name')
    
        json.dumps(list(job_reports))
    
    0 讨论(0)
  • 2020-12-02 07:54

    The .values() 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
    
    0 讨论(0)
  • 2020-12-02 08:01

    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...
    
    0 讨论(0)
  • 2020-12-02 08:01

    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
    
    0 讨论(0)
  • 2020-12-02 08:03

    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 ...

    0 讨论(0)
提交回复
热议问题