Answer a question

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.

so i had filtered something like below

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()]

So as we can observe above we are creating a list by filtering a queryset, but i want the result as a queryset.

So is there any way to convert the list to queryset object ?

Answers

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)
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐