在外键中使用 Django bulk_create 对象? [英] Using Django bulk_create objects in foreign keys?

查看:33
本文介绍了在外键中使用 Django bulk_create 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Django bulk_create 及其一些缺陷":

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 the pre_save and post_save signals will not be sent.
2. It does not work with child models in a multi-table inheritance scenario.
3. If the model's primary key is an AutoField it does not retrieve and set the primary key attribute, as save() does.
"

我没有完全理解它.因此,如果我有一个对象列表,请将其传递给 bulk_create:

I didn't fully understand it. So if I have a list of objects, pass it into bulk_create:

objList = [a, b, c,] #none are saved
model.objects.bulk_create(objList)

我还能在外键中使用这些对象吗?

Could I still use these objects in foreign keys fine?

for obj in objList:
    o = otherModel(something='asdfasdf', fkey=obj)
    o.save() # will this be fine given the caveats stated above?

那么foreignKey 关系会好吗?同样,当它说 2. 它不适用于多表继承场景中的子模型时,这意味着从另一个模型(抽象与否)继承的任何模型都不能使用bulk_create?

So will the foreignKey relation be okay? Also when it says 2. It does not work with child models in a multi-table inheritance scenario, it means that any model that inherits from another model(abstract or not) cannot use bulk_create?

推荐答案

尝试手动设置 ID.为防止竞争条件,请确保将该函数包装为单个事务.

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()

请注意,此方法不适用于具有 serial 字段或其他自动递增的数据库内生成键的任何表.由于 Django 端正在生成 ID,因此批量创建不会增加密钥.

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.

这篇关于在外键中使用 Django bulk_create 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆