How to convert a list in to queryset django
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)
The previous answers are correct if each list item already exists in the database, but sometimes this is not the case. In this case you can create a queryset stub based on the list and implement queryset-methods and queryset-properties as needed.
class ListAsQuerySet(list):
def __init__(self, *args, model, **kwargs):
self.model = model
super().__init__(*args, **kwargs)
def filter(self, *args, **kwargs):
return self # filter ignoring, but you can impl custom filter
def order_by(self, *args, **kwargs):
return self
qs = ListAsQuerySet(custom_list, model=Post)
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)