Search code examples
djangodjango-filter

Django filter dynamic field name based on queryset


I have a queryset with several annotations, including two fields: price and price_after_discount. I want to implement a max_filter based on a specific value. However, I need to handle a condition: if the price_after_discount field is not equal to 0, the filter should be applied on that field; otherwise, the filter should be applied on the price field.

I've attempted the following code, although it's not functioning correctly. This is a sample code:

value = 200
queryset.filter(
    Case(
        When(price_after_discount=0, then=F("price")),
        default=F("price_after_discount")
    )__lt=value
)

Can you please provide guidance on how to properly implement this max_filter condition based on the price_after_discount and price fields?


Solution

  • You use an .alias(…) [Django-doc] for the expression, and then .filter(…) [Django-doc] on that alias:

    queryset.alias(
        my_price=Case(
            When(price_after_static_discount=0, then=F('price')),
            default=F('price_after_discount'),
        )
    ).filter(my_price__lt=value)