0

嗨(对不起我的英语不好)!

当我做这个时:

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

谢谢 !:)

4

2 回答 2

1

我不认为你真的需要额外的。从 Django 的概念来看,您不需要在运行 Django QuerySet 时挑选特定的列。该逻辑可以在模板端完成。

我假设您知道如何galley_qs从您的视图推送到您的模板:

# views.py
gallery_qs = Gallery.objects.all()\
                .annotate(Count('photos'))

在您的模板/html中:

{% for gallery in gallery_qs %}
    {% for photo in gallery.photos %}

    {% endfor %}
{% endfor %}

photos是您画廊模型中的 ManyToManyField。

于 2009-09-03T20:43:03.347 回答
0

当画廊与照片 ID 是多对多关系时,为什么要尝试获取带有 photo_id 注释的不同画廊记录?据我所知,您正在执行的查询只会为每个画廊获得一个照片 ID。

如果您确实需要执行上述操作,我认为您可以使用 distinct() 来获取不同的画廊记录(顺便说一句,您不需要其中的“all()”)。

Gallery.objects.distinct()\
               .annotate(Count('photos'))\
               .extra(select={'photo_id': 'photologue_photo.id'})

或者您可以直接访问照片 ID,

g = Gallery.objects.annotate(Count('photos'))
# Get the photo
photo = g.photos[0]
于 2009-09-04T00:30:47.250 回答