Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list in to 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.

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 ?

like image 825
Shiva Krishna Bavandla Avatar asked Sep 04 '13 07:09

Shiva Krishna Bavandla


People also ask

How do I convert a list to a Queryset?

To convert a list back to a queryset with Python Django, we can use the filter method. to call filter with the pk__in argument set to the list_of_ids list to get all model objects with the primary key in the list_of_ids .

Is django Queryset a list?

A QuerySet is, in essence, a list of objects of a given Model. QuerySets allow you to read the data from the database, filter it and order it.

What is Queryset in django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


2 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)
like image 147
Paulo Almeida Avatar answered Sep 22 '22 13:09

Paulo Almeida


Actually i had found one way by googling, but this may take a lot of time for querying/generating results if there are huge number of records

custom_list = [rec.id for rec in posts if 'string_or_field' in rec.tags.all()]

querset = MyModel.objects.filter(id__in=custom_list)
like image 34
Shiva Krishna Bavandla Avatar answered Sep 21 '22 13:09

Shiva Krishna Bavandla