How to convert a list in to queryset django

前端 未结 4 652
盖世英雄少女心
盖世英雄少女心 2021-02-04 09:27

I have a queryset(which is filtered actually) as below

posts = [, , , , 

        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 09:33

    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)
    

提交回复
热议问题