2

我有两个模型:IndustryEmployer,如下所示:

class Industry(models.Model):
    name = models.CharField(max_length=255, unique=True)


class Employer(models.Model):
    industry = models.ForeignKey(Industry)
    name = models.CharField(max_length=255, unique=True)

问题是,并非所有行业都有雇主……我想获得一份至少有一个雇主映射到他们的所有行业的列表,而不是全部获得。使用 ORM 而不是仅使用常规 SQL 是否可以做到这一点?我试图在 django 文档和 coudlnt 中找到它。

4

1 回答 1

2

这是Django Annotations的经典问题

尝试:

from django.db.models import Count
Industry.objects.annotate(num_employers=Count('employer').filter(num_employers__gt=0)
于 2013-06-24T16:08:31.517 回答