Using Django bulk_create objects in foreign keys?

后端 未结 2 1908
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-06 00:48

I was reading up on Django bulk_create and a few of its \"flaws\":

\"
This has a number of caveats though:

1. The model\'s save() method will not be called, and         


        
2条回答
  •  悲&欢浪女
    2021-02-06 01:02

    Try setting the ids manually. To prevent race conditions, make sure to wrap the function as a single transaction.

    from django.db import transaction, models
    
    @transaction.commit_on_success
    def bulk_create_with_manual_ids(foo_list):
        id_start = (Foo.objects.all().aggregate(models.Max('id'))['id__max'] or 0) + 1
        for i,foo in enumerate(foo_list): foo.id = id_start + i
        return Foo.objects.bulk_create(foo_list)
    
    objList = [Foo(),Foo(),Foo()]
    foo_objects = bulk_create_with_manual_ids(objList)
    Bar(foo=foo_objects[0]).save()
    

    Note that this approach is unsuitable for any table that has a serial field or other auto-incrementing in-database generated key. The key will not be incremented by the bulk create since IDs are being generated on the Django side.

提交回复
热议问题