首页 > 解决方案 > 使用 Django 的 bulk_create() 方法时出错

问题描述

我正在尝试使用数据库表中的Djangobulk_create()方法批量创建一些条目。在我将创建的列表传递到那里的最后一步出现错误,因此显然没有记录被保存。TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

下面是我试图将记录保存在数据库表中的代码。

类方法

@classmethod
def mark_all_added(cls, id: int, spec_id: int) -> None:
    spec_ids = set(
        cls.objects.filter(spec_id=spec_id)
        .values_list("id")
    )

    through_objects = [
        cls.added_by.through(id=id, spec_id=sid)
        for sid in spec_ids
    ]

    cls.added_by.through.objects.bulk_create(through_objects) # getting error on this line

有人可以帮助突出我的错误或告诉我如何在保存批量记录的同时解决此问题。我知道我犯了一个愚蠢的错误,但我无法追踪它。任何一种都将不胜感激。提前致谢。

标签: pythondjangodjango-modelsdjango-rest-framework

解决方案


您需要通过在方法 [Django-doc]中指定来制作 s 的平面列表'id',而不是单例元组,因此:QuerySetflat=True.values_list(…)

@classmethod
def mark_all_added(cls, id: int, spec_id: int) -> None:
    spec_ids = set(
        cls.objects.filter(spec_id=spec_id)
        .values_list('id', flat=True)  # ← use flat=True
    )
    # …

推荐阅读