【发布时间】:2009-09-02 10:38:01
【问题描述】:
对不起,我的英语很丑)!
想象一下这些非常简单的模型:
class Photo(models.Model):
is_public = models.BooleanField('Public', default=False)
class Gallery(models.Model):
photos = models.ManyToManyField('Photos', related_name='galleries', null=True, blank=True)
我需要选择所有包含至少张公共照片的Gallery 实例(如果可能,添加一个包含公共照片数量的photos__count 属性)。
我试过这个查询:
Gallery.objects.all()\
.annotate(Count('photos'))\
.filter(photos__is_public=True)
似乎还可以,但是:
- 查询很奇怪
- 在每个图库上添加的属性photos__count 将包含此图库中的照片总数,而不是此图库中的公共照片数量。
我认为我需要的硬编码 sql 查询是:
SELECT `gallery`.* , COUNT(`gallery_photos`.`photo_id`)
FROM `gallery`
INNER JOIN `gallery_photos` ON (`gallery`.`id` = `gallery_photos`.`gallery_id`)
INNER JOIN `photo` ON (`gallery_photos`.`photo_id` = `photo`.`id`)
WHERE `photo`.`is_public` = True
GROUP BY gallery.id ;
有解决办法吗?
谢谢! ;-)
【问题讨论】:
标签: python sql django django-models count