简体   繁体   中英

Bulk create Django with unique sequences or values per record?

I have what is essentially a table which is a pool of available codes/sequences for unique keys when I create records elsewhere in the DB. Right now I run a transaction where I might grab 5000 codes out of an available pool of 1 billion codes using the slice operator [:code_count] where code_count == 5000.

This works fine, but then for every insert, I have to run through each code and insert it into the record manually when I use the code.

Is there a better way?

Example code (omitting other attributes for each new_item that are similar to all new_items):

code_count=5000
pool_cds = CodePool.objects.filter(free_indicator=True)[:code_count]

        for pool_cd in pool_cds:

            new_item = Item.objects.create(
                pool_cd=pool_cd.unique_code,
            )
            new_item.save()


        cursor = connection.cursor()
        update_sql = 'update CodePool set free_ind=%s where pool_cd.id in %s'
        instance_param = ()

        #Create ridiculously long list of params (5000 items)
        for pool_cd in pool_cds:
            instance_param = instance_param + (pool_cd.id,)
        params = [False, instance_param]
        rows = cursor.execute(update_sql, params)

As I understand how it works:

code_count=5000
pool_cds = CodePool.objects.filter(free_indicator=True)[:code_count]
ids = []

for pool_cd in pool_cds:
    Item.objects.create(pool_cd=pool_cd.unique_code)
    ids += [pool_cd.id]

CodePool.objects.filter(id__in=ids).update(free_ind=False)

By the way if you created object using queryset method create, you don't need call save method. See docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM