如何编写一个Django查询,其中的条件是相关项的计数?

2024-10-03 04:34:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是Django和python3.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.

Tags: djangoidfalsedefaultmodelobjectsonmodels
1条回答
网友
1楼 · 发布于 2024-10-03 04:34:40

Use annotate then filter

from django.db.models import Count

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

更新-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)

相关问题 更多 >