How to convert a list in to queryset django

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

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

posts = [, , , , 

        
4条回答
  •  借酒劲吻你
    2021-02-04 09:44

    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)
    

提交回复
热议问题