[Django]-How to create and save object in bulk for dictionary in Django

4👍

You can try something along the following lines which will only create 2 db hits:

def create_obj(response):
    # 1st db query: existing fees instances form response
    existing = Fees.objects.filter(rollno__in=response.keys())

    keys = set(f.rollno for f in existing)

    # 2nd db query: bulk create non-existing
    new = Fees.objects.bulk_create([
         Fees(**{ke.lower(): va for ke, va in value.items()})
         for key, value in response.items() if key not in keys
    ])

    yield from existing
    yield from new

Leave a comment