Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Querysets - Filter objects by Boolean values in a related object

I would like to create a model manager for my Purchase model:

class Purchase(models.Model)
    number = models.IntegerField

class InventoryLog(models.Model)
    purchase = models.ForeignKey(Purchase)
    sold_out = models.BooleanField(default=false)

I would like my model manager to return any Purchase objects that are not related to an InventoryLog object with a sold_out value of True

Is there a way to handle this with a queryset, Q object or F object, or will I need to resort to a for loop?

like image 881
Adam Starrh Avatar asked Oct 15 '25 16:10

Adam Starrh


1 Answers

I believe Purchase.objects().exclude(inventorylog__sold_out=True) will do that.

like image 177
Peter DeGlopper Avatar answered Oct 17 '25 11:10

Peter DeGlopper