Django: how to add compare condition in annotate queryset
<p>I want to add compare operations in annotate queryset to calculate value for specific field. How can I do that?
This is my annotate queryset</p>

<pre><code>sale_item_list = OrderItem.objects.filter(order_id=order.id) \
                .values('item__name') \
                .annotate(price=F('price')) \
                .annotate(exchange_rate=F('exchange_rate')) \
                .annotate(quantity=F('quantity') \
.annotate(amount=Case(
                        When(F('quantity') &lt; F('inventory'), then=Sum(F('quantity') * F('price'))),
                        When(F('quantity') &gt; F('inventory'), then=Sum(F('inventory') * F('price'))),
                        output_field=IntegerField()))
</code></pre>

<p>Conditional Expressions of my queryset above run error. Please help me fix it?</p>

<p>Try using the lesser and greater than field lookups <code>__gt</code> and <code>__lt</code>:</p>

<pre><code>When(quantity__lt=inventory, then=Sum(F('quantity') * F('price'))),
When(quantity__gt=inventory, then=Sum(F('inventory') * F('price'))),
</code></pre>

<p>See <a href="https://docs.djangoproject.com/el/1.10/ref/models/querysets/#gt" rel="nofollow">https://docs.djangoproject.com/el/1.10/ref/models/querysets/#gt</a></p>

python django python-3.x