如何在django中执行计数和加入?

时间:2010-10-15 06:19:47

标签: django postgresql django-models

如何使用模型执行连接和计数查询,如下所示:

select count(*),site_url from connection_ss 
   join site_ss on to_id_id = site_id 
        where site_ss.source_id = 1 group by site_url order by count desc

以下是我的模特:

class site(models.Model):
    site_id = models.AutoField(primary_key=True)
    site_url = models.URLField(unique=True)
    human_verified = models.BooleanField(default=False)
    last_entry2 = models.DateTimeField(default='2009-01-01')
    source_id = models.ForeignKey(source)
    author_alias = models.TextField()

class connection(models.Model):
    from_id = models.ForeignKey(site,related_name="from_get")
    to_id = models.ForeignKey(site,related_name = "to_get")

    class Meta:
        db_table = "connection_ss"
        unique_together = (("from_id","to_id"),)

1 个答案:

答案 0 :(得分:3)

您要找的是 Aggregation/annotation 。使用Count对象,您可以执行以下操作:

Connection.objects.filter(site__to__source=1).annotate(Count('site_url')).order_by('-count')

请注意,这不起作用,因为我并不真正了解您尝试获取的对象是什么,但我希望这将有助于作为指南