updated January 31, 2020
Django QuerySet how to...
1. How to replace EXIST
raw SQL with QuerySet.filter()
call
class Order(models.Model): pass class Item(models.Model): order = models.ForeignKey(Order, related_name='items')How to get empty orders:
Order.objects.extra(where=["NOT EXISTS (SELECT * FROM item WHERE order_id = order.id)"])Another option, produces query with LEFT OUTER JOIN:
Order.objects.filter(items__isnull=True)
2. How to add relation table into QuerySet SQL query
How to add relation table into resulting query for QuerySet: add related field in theselect_related()
call:
Item.objects.select_related('order')The resulting SQL contains the order table JOIN.
3. How to make union of 2 QuerySets for different models
Usevalues_list()
with same count of columns, columns at same positions should be of same type:
Car.objects.values_list('price', 'quantity').union( Bicycle.objects.values_list('price', 'quantity') )