嗨(对不起我的英语不好)!
当我做这个时:
gallery_qs = Gallery.objects.all()\
.annotate(Count('photos'))\
.extra(select={'photo_id': 'photologue_photo.id'})
sql查询是:
SELECT (photologue_photo.id) AS `photo`, `photologue_gallery`.*
FROM `photologue_gallery`
LEFT OUTER JOIN `photologue_gallery_photos`
ON (`photologue_gallery`.`id` = `photologue_gallery_photos`.`gallery_id`)
LEFT OUTER JOIN `photologue_photo`
ON (`photologue_gallery_photos`.`photo_id` = `photologue_photo`.`id`)
GROUP BY `photologue_gallery`.`id`, photologue_photo.id
ORDER BY `photologue_gallery`.`publication_date` DESC
问题是该extra
方法会在 GROUP BY 子句中自动添加 photologue_photo.id 。我需要删除它,因为它复制了画廊,例如:
[<Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>, <Gallery: Lorem ipsum dolor sit amet>]
我需要用 django 进行这个查询,这可能吗?
SELECT (photologue_photo.id) AS `photo`, `photologue_gallery`.*
FROM `photologue_gallery`
LEFT OUTER JOIN `photologue_gallery_photos`
ON (`photologue_gallery`.`id` = `photologue_gallery_photos`.`gallery_id`)
LEFT OUTER JOIN `photologue_photo`
ON (`photologue_gallery_photos`.`photo_id` = `photologue_photo`.`id`)
GROUP BY `photologue_gallery`
ORDER BY `photologue_gallery`.`publication_date` DESC
谢谢 !:)