【问题标题】:Filtering based on .count() of a forgein key field in Django querysets基于 Django 查询集中外键字段的 .count() 进行过滤
【发布时间】:2011-12-25 12:12:20
【问题描述】:

所以我有一些像这样的 Django 1.3 模型:

class Type(models.Model):
  is_bulk = models.BooleanField()

class Component(models.Model):
  parent = models.ForeignKey(Type)

有些 Type 有 0 个 Component,有些有 1 或 2,等等。我如何编写一个 QuerySet 来过滤所有具有 > 0 个组件的类型。即排除具有 0 个组件的类型?

【问题讨论】:

    标签: django orm django-queryset django-orm


    【解决方案1】:
    from django.db.models import Count
    Type.objects.annotate(component_count=Count('component')).exclude(component_count=0)
    

    【讨论】:

      猜你喜欢
      • 2019-01-12
      • 2017-03-09
      • 2019-02-17
      • 2013-09-17
      • 2015-07-30
      • 2021-10-16
      • 2020-10-22
      • 2019-10-19
      • 1970-01-01
      相关资源
      最近更新 更多