0

当一个字符串列表(代表标签)被发送到一个函数时,它会检索数据库中的标签,并创建在数据库中找不到的标签。

然后我需要将这两个组合成一个查询集并返回,但是当我尝试使用 + 连接两个查询集时,它会引发错误。

如何连接两个查询集?

# Separate one in DB and not in DB
tags_found_in_db = Tag.objects.filter(name__in = tag_strings)
name_of_tags_found_in_db = [tag.name for tag in tags_found_in_db]
tags_not_in_db = list(set(tag_strings) - set(name_of_tags_found_in_db))

# Bulk Create
tags_to_be_created = []

for new_tag_name in tags_not_in_db:
  tags_to_be_created.append(
    Tag(name = new_tag_name)
  )
new_tags = Tag.objects.bulk_create( tags_to_be_created )

# > TypeError: can only concatenate list (not "QuerySet") to list
return new_tags + tags_found_in_db
4

2 回答 2

1

解决方案

不需要组合任何东西,只需返回tags_found_in_db查询集是惰性的。

但是,如果绝对需要这样做,请使用.union方法 Queryset 对象来组合 Queryset。

笔记

bulk_create不返回 Queryset 对象,这.union对您的用例来说更不实用。

参考

Django 查询集是惰性的: https ://docs.djangoproject.com/en/3.1/topics/db/queries/#querysets-are-lazy

Django 查询集联盟:https ://docs.djangoproject.com/en/3.1/ref/models/querysets/#union

于 2020-10-10T12:27:00.277 回答
1

由于错误表明上述参数之一是 QuerySet,您需要将其转换为列表。检查其中哪一个是 QuerySet 以及为什么它没有转换为列表。

也不是返回:

return new_tags + tags_found_in_db

您可以返回 Tag.objects.all() - 它应该返回相同的结果。如果您确实需要连接查询集,请查看这篇文章

于 2020-10-10T14:45:46.210 回答