1👍
You can use CASE, WHEN for this if you are writing raw sql and getting the output is rather easy but django calls for a bit of work.
SELECT A.*, CASE WHEN credit_limit = 0 THEN 10000
ELSE
(available_credit * 100 / credit_limit)::integer
END as percent_available from
(SELECT
a.id, ....) AS A
It would be wholly incorrect to report available percentage as zero when credit_limit is zero. You shoudl report it to the user as N/A or something else.
Getting back to django, you would use the CASE expression for this.
A Case() expression is like the if … elif … else statement in
Python. Each condition in the provided When() objects is evaluated in
order, until one evaluates to a truthful value. The result expression
from the matching When() object is returned.
Now suppose your model was named Credit, then the query might be.
Credit.objects.all().annotate(credit_available =
Case(
When(credit_limit = 0, Then value 10000)
default = F('available_credit')*100/F('credit_limit'))
)
👤e4c5
0👍
Use CASE
SELECT *, CASE WHEN (credit_limit = 0) THEN /* code */ ELSE /* code */ END AS
percent_available FROM ...
Source:stackexchange.com