I’m after a django query that will allow me to list all items which do and do-not have any certain related objects.
For example if I have the models:
def Customer(Model):
name = CharField(...)
...
def Order(Model):
customer = ForeignKey(Customer)
Now, how do I say “Give me all customers with orders, and conversely, give me all customers without orders”?
What I have so far (which doesn’t work) is this:
withords = model.objects.all().annotate(orders=Count('order')).filter(orders__gt=0)
without = model.objects.all().annotate(orders=Count('order')).filter(orders__lt=1)
Any ideas?
How about:
All customers with orders:
Customer.objects.filter(order__isnull=False).distinct()All customers without orders:
Customer.objects.filter(order__isnull=True)