Search code examples
djangodjango-modelsdjango-querysetdjango-database-functions

Filter an object that has multiple related objects in Django


Let's say I have two models that have one-to-many relationships as the code below. I'd like to only get order objects that have more than one shipment object.

The only way I can think of is getting it through a list comprehension [order for order in Order.objects.all() if order.shipments.count() > 1] but it seems too inefficient.

Is there a better way of doing this query in Django?

class Order(models.Model):
    name = models.CharField(max_length=20)
    store = models.CharField(max_length=20)

class Shipment(models.Model):
    order = models.ForeignKey(Order, related_name='shipments')

Solution

  • this should do it:

    you can access shipments via the related name:

    Order.objects.annotate(num_shipments=Count('shipments')).filter(num_shipments__gt=1)