Using Django bulk_create objects in foreign keys?

前提是你 提交于 2019-12-03 02:52:00
egafni

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.

For the first question, no you won't be able to do that, because obj won't have its primary key set so couldn't be used as a foreign key.

The second question, no that's not what it says at all. It specifically mentions "multi-table inheritance": inheriting from an abstract model is not multi-table inheritance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!