Search code examples
pythondjangodatabasefiltermodels

How do I do a math filter in Django database request?


I've got a model which has the following columns in database: "corrects" and "incorrects".

I want to do a filter that takes only the > 80%.

F.e: (corrects * 100 / (corrects + incorrects)) > 80

How do I do this?


Solution

  • Use F (documentation) expressions to annotate, then filter on the annotation:

    from django.db.models import F
    
    YourModel.objects.annotate(ratio=100*F('corrects')/(F('corrects')+F('incorrects')))
                     .filter(ratio__gt=80)