Django order items by two fields, but ignoring them if they're zero

前端 未结 2 2046
终归单人心
终归单人心 2021-02-12 19:12

I have the following model (greatly simplified for the purposes of this question):

class Product(models.Model):
    price = models.DecimalField(max_digits=8, dec         


        
2条回答
  •  盖世英雄少女心
    2021-02-12 19:32

    If you stumble upon this requirement and happen to be using Django 1.8 and higher, you can use django.db.models.functions.Coalesce for a slightly nicer, cross db-engine, solution:

    from django.db.models.functions import Coalesce
    
    Product.objects.annotate(
        current_price=Coalesce('sale_price', 'price')
    ).order_by('-current_price')
    

提交回复
热议问题