Django related query filter, searching for items with or without related items

I get a django request that will allow me to list all the elements that do and do - do not have any specific related objects.

For example, if I have models:

def Customer(Model): name = CharField(...) ... def Order(Model): customer = ForeignKey(Customer) 

Now, how can I say, โ€œGive me all customers with orders and, conversely, give me all customers without ordersโ€?

What I still have (which does not work):

 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?

+4
source share
1 answer

What about:

All customers with orders:

Customer.objects.filter(order__isnull=False).distinct()

All customers without orders:

Customer.objects.filter(order__isnull=True)

+6
source

Source: https://habr.com/ru/post/1414776/


All Articles