开发者

Distinct in many-to-many relation

开发者 https://www.devze.com 2023-01-17 20:50 出处:网络
class Order(models.Model): 开发者_StackOverflow... class OrderItem(models.Model) order = models.ForeignKey(Order)
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

精彩评论

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