How to combine two or more querysets in a Django view?

后端 未结 13 2434
猫巷女王i
猫巷女王i 2020-11-21 22:40

I am trying to build the search for a Django site I am building, and in that search, I am searching in 3 different models. And to get pagination on the search result list, I

13条回答
  •  别那么骄傲
    2020-11-21 23:33

    DATE_FIELD_MAPPING = {
        Model1: 'date',
        Model2: 'pubdate',
    }
    
    def my_key_func(obj):
        return getattr(obj, DATE_FIELD_MAPPING[type(obj)])
    
    And then sorted(chain(Model1.objects.all(), Model2.objects.all()), key=my_key_func)
    

    Quoted from https://groups.google.com/forum/#!topic/django-users/6wUNuJa4jVw. See Alex Gaynor

提交回复
热议问题