Filter by fields of the same model


I need to know how I can filter in a model that is an Invoice where I have two fields to pay and another that is paid, I have to do a filter to get the bills that have different amounts than paid to know which of the bills are unpaid.

class Facturas(models.Model):
    factura= models.CharField(max_length=250, unique=True)
    unidadM = models.CharField(max_length=20)
    importeSD = models.DecimalField(max_digits=7, decimal_places=2)
    pagadoSD = models.DecimalField(max_digits=7, decimal_places=2)
    importeEU = models.DecimalField(max_digits=7, decimal_places=2)
    pagadoEU = models.DecimalField(max_digits=7, decimal_places=2)   
    fechaCreacionFact = models.DateTimeField(
    fechaModifFact = models.DateTimeField(null=True, blank=True)

I have done something but it is getting all invoices and then a cycle for to compare the amount with paid and it takes a long time and the connection in the browser drops due to server response delay.

asked by Antonio 29.08.2018 в 15:16

1 answer


You can use F () expressions . These expressions allow you to reference fields of the same model.

In your case I assume that you should look for those whose values in pagadoSD and pagadoEU are less than the values importeSD and importeEU respectively. In that case you also need to use objects Q () to to be able to do a OR at the level of the database:

from django.db.models import F, Q
from .models import Facturas

facturas_sin_pagar = Facturas.objects.filter(
    Q(pagadoSD__lt=F('importeSD')) | Q(pagadoEU__lt=F('importeEU'))

What I'm doing is: "get those bills whose amount paid SD or EU is less than their respective amount".

answered by 29.08.2018 / 16:59