Django: Converting an entire set of a Model's objects into a single dictionary

前端 未结 12 1289
野的像风
野的像风 2020-11-30 16:45

If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.

Is ther

12条回答
  •  攒了一身酷
    2020-11-30 17:24

    You are looking for the Values member of QuerySet which allows you to get a list of dictionaries from your query

    Returns a ValuesQuerySet -- a QuerySet that evaluates to a list of dictionaries instead of model-instance objects. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

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

提交回复
热议问题