I believe that something similar to Room.objects.filter(hospitalization__date_out="2014-04-25", max_persons__lt=x)
should do the trick. Remember that you can have multiple declarations in a filter operation, and that you can also chain both exclusions and filters. This doesn't add to database activity; queryset
filters and the like are only executed when the queryset
itself is evaluated. See The Django Docs on making queries.
EDIT: This actually turned out to be slightly more complicated than I first thought, but I believe I have worked it out (after importing your model declarations and having a shell session!)
rooms = Room.objects.filter(DATE FILTERING HERE).annotate(num_persons=Count('hospitalization__room__id')).filter(num_persons__lt=F('max_persons')).count()
Will give you the number of rooms in which num_persons
(our annotated variable above) is less than max_persons
, with the date filtering occurring beforehand.
Remember to include the required imports:
from django.db.models import Count
from django.db.models import F