views:

35

answers:

1
class Order(models.Model):
    ...

class OrderItem(models.Model)
    order = models.ForeignKey(Order)
    product = models.ForeignKey(Product)
    quantity = models.PositiveIntegerField()

What I need to do is to get the Order(s) which has only one order item. How can I write it using the QuerySet objects (without writing SQL)?

+3  A: 

The easiest way to do this would be to use the Count aggregation:

from django.db.models import Count
Order.objects.annotate(count = Count('orderitem__id')).filter(count = 1)
Manoj Govindan