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 ?
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 .
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.
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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With