Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter for max difference between 2 columns

Tags:

django

I have a table named RoundTable and it has 2 fields, the max number of seats and the number of currently occupied seats. I want to find the max difference between these two columns.

My model:

class RoundTable(models.Model):
    total_seats = models.SmallIntegerField(validators=[MinValueValidator(1)])
    occupied_seats = models.SmallIntegerField(validators=[MinValueValidator(1)])
    .... other fields

What would the query be like?

RoundTable.objects.aggregate(?)

like image 560
Rgfvfk Iff Avatar asked Nov 19 '25 20:11

Rgfvfk Iff


2 Answers

It should be something like:

from django.db.models import F, Max

RoundTable.objects
    .annotate(diff=F('total_seats')-F('occupied_seats'))
    .aggregate(Max('diff'))
like image 171
Todor Avatar answered Nov 21 '25 08:11

Todor


Try this,

from django.db.models import Max, F, ExpressionWrapper, IntegerField

RoundTable.objects.annotate(diff=ExpressionWrapper(
    F('total_seats') - F('occupied_seats'), output_field=IntegerField()
)).aggregate(max=Max('diff'))
like image 34
JPG Avatar answered Nov 21 '25 08:11

JPG