如何连接两个Django模型查询集

时间:2020-10-10 12:14:48

标签: python django django-models

将字符串列表(表示标签)发送给函数时,它会检索DB中的标签,并检索在db中找不到的标签箱。

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

如何连接两个查询集?

# 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

2 个答案:

答案 0 :(得分:1)

解决方案

无需合并任何内容,只需返回tags_found_in_db,因为Querysets是惰性的。

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

注释

bulk_create不会返回Queryset对象,从而使.union在您的用例中不那么实用。

参考

Django查询集很懒:https://docs.djangoproject.com/en/3.1/topics/db/queries/#querysets-are-lazy

Django Queryset Union:https://docs.djangoproject.com/en/3.1/ref/models/querysets/#union

答案 1 :(得分:1)

由于错误提示,上面的参数之一是QuerySet,您需要将其转换为list。检查其中哪个是QuerySet以及为什么不将其转换为列表。

也不要返回:

return new_tags + tags_found_in_db

您可以返回Tag.objects.all()-它应该返回相同的结果。如果您确实需要串联查询集check this article