您如何编写Django查询条件(如果有COUNT个相关项目)?

时间:2019-04-09 17:23:41

标签: python django python-3.x count foreign-keys

我正在使用Django和Python 3.7。我有这两种模型,它们通过外键相互关联...

class Website(models.Model):
    objects = WebsiteManager()
    path = models.CharField(max_length=100)



class Article(models.Model):
    website = models.ForeignKey(Website, on_delete=models.CASCADE, related_name='articlesite')
    title = models.TextField(default='', null=False)
    url = models.TextField(default='', null=False)
    created_on = models.DateTimeField(db_index=True, default=datetime.now)

我想编写一个Django查询,该查询返回绑定了100多个文章的网站。在PostGres中,我可以编写此查询

select w.id, count(*) FROM website w, article a where w.id = a.website_id group by w.id;

但是我不清楚如何使用Django查询来执行此操作。如果条件为COUNT,该如何写查询?

编辑:

我修改了查询以添加条件...

qset = Website.objects.annotate(articlesite_count=Count('articlesite')).filter(
                         articlesite__edited_date__null=True,
                         articlesite_count__gte=100)

但是现在这会导致错误

Unsupported lookup 'null' for DateTimeField or join on the field not permitted.

1 个答案:

答案 0 :(得分:2)

Use annotate then filter

from django.db.models import Count

Website.objects.annotate(articlesite_count=Count('articlesite')).filter(articlesite_count__gte=100)

UPDATE-1

from django.db.models import Count

Website.objects.filter(articlesite__edited_date__isnull=True).annotate(
    articlesite_count=Count('articlesite')).filter(
    articlesite_count__gte=100)