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

前端 未结 9 554
臣服心动
臣服心动 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 08:03

    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.

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

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

    Simply put list(yourQuerySet).

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