Django,Python:批量创建几个依赖项

时间:2018-04-13 12:23:33

标签: python django

我有很多依赖项(Group->Link->Match) - 我无法创建一个没有ForeignKey ID的新对象。

有方法是简化或加快这项操作吗? 我可以创建一个保存所需依赖项的大对象吗?我试图通过bulk_create来做 - 但与id相同的问题。

    groups = template.get('groups')
    allMatchObjs = []
    if groups:
        for group in groups:
            groupObj = Group.objects.create(name=group['name'])
            links = group.get('links')
            if links:
                for link in links:
                    linkObj = Link.objects.create(
                        group=groupObj, 
                        name=link['name']
                    matches = link.get('matches')
                    if matches:
                        matchObjs = (Match(
                                        name=match['name'],
                                        link=linkObj) for match in matches)
                        allMatchObjs.extend(matchObjs)

    Match.objects.bulk_create(allMatchObjs)

1 个答案:

答案 0 :(得分:1)

根据每个级别的元素数量,这可能会提高速度:

groups = template.get('groups')
allMatchObjs = []
if groups:
    group_models = [
        Group(name=group['name']
        for group in groups
    ]
    Group.objects.bulk_create(new_groups)

    for g, g_model in zip(groups, group_models):
        links = g.get('links')
        if links:
            link_models = [
                Link(group=g_model, name=link['name'])
                for link in links
            ]
            Link.objects.bulk_create(link_models)

            for l, l_model in zip(links, link_models)
                matches = link.get('matches')
                if matches:
                    matchObjs = [
                        Match(name=match['name'], link=l_model)
                        for match in matches
                    ]
                    allMatchObjs.extend(matchObjs)

Match.objects.bulk_create(allMatchObjs)

因此,您将在每个级别使用bulk_create,但不会在中间级别的单个批次中使用。{/ p>

<强>更新

更好:

groups = template.get('groups')

if groups:
    allGroups = [
        Group(name=group['name']
        for group in groups
    ]

Group.objects.bulk_create(allGroups)

allLinks = []
zipped_links = []
for g, g_model in zip(groups, allGroups):
    links = g.get('links')
    if links:
        link_objs = [
            Link(group=g_model, name=link['name'])
            for link in links
        ]

        allLinks.extend(link_objs)

        zipped_links.extend(zip(links, link_objs))

Link.objects.bulk_create(allLinks)                

allMatchObjs = []
for link, l_model in zipped_links:
    matches = link.get('matches')
    if matches:
        matchObjs = [
            Match(name=match['name'], link=l_model)
            for match in matches
        ]
        allMatchObjs.extend(matchObjs)

Match.objects.bulk_create(allMatchObjs)

现在你真的为每个级别使用一个bulk_create。