Django query - exclude based on a choice

Hello All.

I have this model:

class ordenGeneral (models.Model):
  
    id = models.AutoField(primary_key=True)

    client_email = models.EmailField(blank=True)

    proveedor_email=models.EmailField(blank=True)

    rubro= models.ForeignKey(item,default=None,on_delete=models.CASCADE)

    tiempo_respuesta_promedio=models.FloatField(default=1000)

    fecha_creacion=models.DateField( auto_now_add=True)

    ticket =  models.IntegerField(default=1000, blank=True)

    STATUS = [

        ("ENV","ENVIADA"),

        ("REC","RECIBIDA"),

        ("ACE","ACEPTADA"),

        ("EVI","EN VIAJE"),

        ("ENS","EN SITIO"),

        ("RED","REALIZADA"),

        ("CAN","CANCELADA"),

        ("REX","RECHAZADA"),

    ]

    status = models.CharField(max_length=3,choices= STATUS,default= "SO")

       

    location_lat = models.FloatField(default=None, blank=True)

    location_long = models.FloatField(default=None, blank=True)

    day = models.DateField(default=None, blank=True)

    time = models.TimeField(default=None, blank=True)

    tituloPedido = models.TextField(default="Solicitud de pedido")

    problem_description = models.TextField(default=None, blank=True)

    picture1=models.ImageField(default=None, blank=True)

    picture2=models.ImageField(default=None,blank=True)

How can I perform a search and exclude orders with a status of REALIZADA, CANCELADA O RECHAZADA? Like this:

ordenGeneral.objects.filter(proveedor_email=email).exclude(status="CAN", status="REX", status="RED")

The issue here is that all the clauses in a filter or exclude are “AND” joined, not “OR”.

You need to either:

  • Construct the exclude clause using Q objects to “OR” the conditions. (e.g. exclude(Q(status=“CAN”) | Q(status=“REX”) | Q(status=“RED”))
    or
  • Use multiple exclude clauses. (e.g. exclude(status=“CAN”).exclude(status=“REX”).exclude(status=“RED”) )
1 Like