python - 使用 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
有人可以帮助突出我的错误或告诉我如何在保存批量记录的同时解决此问题。我知道我犯了一个愚蠢的错误,但我无法追踪它。任何一种都将不胜感激。提前致谢。
解决方案
您需要通过在方法 [Django-doc]中指定来制作 s 的平面列表'id'
,而不是单例元组,因此:QuerySet
flat=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
)
# …
推荐阅读
- objective-c - ios 13 - 带有 UISearchBar _searchField 的自定义 SearchBar 不起作用
- java - System.arraycopy 性能
- c# - 实体之间通过服务层进行通信
- python - 如何添加带有回调功能的 WeakValueDictionary?
- android - 启用/禁用夜间模式时如何从另一个活动重新创建活动?
- python - 如何通过“ResourceNotFound:请求的资源不存在”错误
- reactjs - 我在哪里可以找到我的 projet 在反应中的文件夹,我在我的桌面上看不到它
- python - 使用 pandas 数据框中的特征创建计算器
- excel - excel中有没有一种方法可以使用公式、vb或c#添加行或移动行
- tsql - 添加日期相同的列的两个值?