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

前端 未结 12 1285
野的像风
野的像风 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条回答
  •  -上瘾入骨i
    2020-11-30 17:35

    use

    dict(((m.key, m.value) for m in DictModel.objects.all())
    

    As suggested by Tom Leys, we do not need to get whole object, we can get only those values we need e.g.

    dict(((m['key'], m['value']) for m in DictModel.objects.values('key', 'value')))
    

    and if you need all values, it is better to keep whole object in dict e.g.

    dict(((m.key, m) for m in DictModel.objects.all())
    

提交回复
热议问题