Search code examples
djangodjango-modelsdjango-orm

Django: bulk update from a list of dicts without constructing the whole query set


I have a list which contains dicts. Something like:

[{'id': 0, 'price': 20}, {'id': 1, 'price': 10}] # a few thousands of elements

how can I update corresponding models without constructing the whole QuerySet?


Solution

  • As of , you can use .bulk_update(…) [Django-doc]:

    data = [{'id': 0, 'price': 20}, {'id': 1, 'price': 10}]
    
    Match.objects.bulk_update([Match(**kv) for kv in data], ['price'])

    We here thus construct Match objects that we then pass to the bulk_update to construct an update query.