开发者

Distinct in many-to-many relation

class Order(models.Model):
    开发者_StackOverflow...

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)?


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜