#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models class ProductQuerySet(models.QuerySet): def sorted_in_stock_by_field(self, field): queryset = self.extra(select={ 'have_stock': 'CASE WHEN (SELECT MAX(in_stock) FROM store_productvariation ' + 'WHERE store_productvariation.product_id = store_product.id) = 0 ' + 'THEN 0 ELSE 1 END' }).order_by('-have_stock', field) return queryset