如何将列表转换为queryset Django [英] How to convert a list in to queryset django
本文介绍了如何将列表转换为queryset Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下的查询集(实际上已被过滤)
I have a queryset(which is filtered actually) as below
posts = [<Post: published>, <Post: needs>, <Post: be>, <Post: issues>, <Post: to>, <Post: tags>]
但是我需要使用来自另一个表/位置等的某些字段来手动过滤上面的查询集.
But i need to filter the above queryset manually with the some field coming from another table/place etc.
所以我过滤了以下内容
custom_list = []
for rec in posts:
if 'string_or_field' in rec.tags.all():
custom_list.extend(rec)
or
custom_list = [rec for rec in posts if 'string_or_field' in rec.tags.all()]
因此,如上所述,我们通过过滤 queryset
创建了一个 list
,但我希望将结果作为 queryset
.
So as we can observe above we are creating a list
by filtering a queryset
, but i want the result as a queryset
.
那么有什么方法可以将 list
转换为 queryset
对象?
So is there any way to convert the list
to queryset
object ?
推荐答案
您可以先查询 Tag
对象,并使用这些ID过滤 Post
:
You can query the Tag
object first and filter Post
with those ids:
tags = Tag.objects.filter(field_name='string_or_field')
posts = Post.objects.filter(tags__in=tags)
这篇关于如何将列表转换为queryset Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文