How to convert a list in to queryset django

[亡魂溺海] 提交于 2021-02-06 02:27:33

问题


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 ?


回答1:


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)



回答2:


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)



回答3:


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)



回答4:


Here's a simple util that you can run to produce a QS from a list:

def list_to_queryset(model, data):
    from django.db.models.base import ModelBase

    if not isinstance(model, ModelBase):
        raise ValueError(
            "%s must be Model" % model
        )
    if not isinstance(data, list):
        raise ValueError(
            "%s must be List Object" % data
        )

    pk_list = [obj.pk for obj in data]
    return model.objects.filter(pk__in=pk_list)


来源:https://stackoverflow.com/questions/18607698/how-to-convert-a-list-in-to-queryset-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!