Фильтр по Count связанного объекта поля Django
Мне нужно отфильтровать доступное оборудование объектов в модели, связанное с полем количества используемого оборудования в другой модели
Мои модели:
""" Available equipments """
class CompanyPersonalProtectiveEquipment(Base):
name = models.CharField(verbose_name="Nome", max_length=255)
description = models.TextField(verbose_name="Descrição")
quantity = models.IntegerField(verbose_name="Quantidade", default=1)
@property
def availability(self):
unavailable_quantity = 0
for personal_protective_equipment in self.patient_personal_protective_equipments.all():
unavailable_quantity += personal_protective_equipment.quantity
return {
"available": self.quantity - unavailable_quantity,
"unavailable": unavailable_quantity
}
""" Used equipments """
class PatientPersonalProtectiveEquipment(Base):
personal_protective_equipment_id = models.ForeignKey(CompanyPersonalProtectiveEquipment, verbose_name="EPI", on_delete=models.CASCADE, related_name="patient_personal_protective_equipments")
date = models.DateField(verbose_name="Data entrega")
quantity = models.IntegerField(verbose_name="Quantidade", default=1)
Поскольку я не могу фильтровать по свойству модели CompanyPersonalProtectiveEquipment, мне нужно фильтровать по связанному количеству PatientPersonalProtectiveEquipment, чтобы получить объекты, у которых количество в наличии меньше x.
small_quantity_comparison = request.data.get("small_quantity_comparison") or 15
small_quantity = CompanyPersonalProtectiveEquipment.objects.filter(quantity_available__lte=small_quantity_comparison)
Есть идеи?