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

前端 未结 12 1286
野的像风
野的像风 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'}]
    
    0 讨论(0)
  • 2020-11-30 17:26
    user = mymodel.objects.all()
    user.values() 
    

    You can also try

    user.values_list() # getting as list
    
    0 讨论(0)
  • 2020-11-30 17:28

    To get values of a models into dictionary, add below code at the place where u need that dictionary

    from models import DictModel
    
    activity_map = dict(Plan.objects.values_list('key', 'value'))
    

    activity_map is a dictionary which contains required information .

    0 讨论(0)
  • 2020-11-30 17:33

    You can use the python serializer:

    from django.core import serializers
    data = serializers.serialize('python', DictModel.objects.all())
    
    0 讨论(0)
  • 2020-11-30 17:34

    You can also rely on django code already written ;).

    from django.forms.models import model_to_dict
    model_to_dict(instance, fields=[], exclude=[])
    
    0 讨论(0)
  • 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())
    
    0 讨论(0)
提交回复
热议问题