【发布时间】:2010-11-11 11:08:46
【问题描述】:
我正在尝试从 syncr 创建的数据中从每个相册中获取随机照片。模型(缩写)如下所示:
class Album(models.Model):
title = models.CharField(max_length=200)
photos = models.ManyToManyField('Photo')
class Photo(models.Model):
title = models.CharField(max_length=200)
我尝试了很多不同的方法,但都没有成功。这是另一个容易的吗?
Take 2:最终代码:
def 画廊(请求,template_name='galleries.html'):
albums = Album.objects.select_related().all()
album_list = []
for album in albums:
album_list.append({'title':album.title, 'id':album.id, 'photo':album.random_photo()})
return render_to_response(template_name, {
"album_list": album_list,
})
【问题讨论】:
-
从所有这些答案中学到了很多,并最终使用了一个组合。非常感谢所有: def gallery(request, template_name='galleries.html'): albums = Album.objects.select_related().all() album_list = [] 专辑中的专辑:album_list.append({'title': album.title, 'id':album.id, 'photo':album.random_photo()}) return render_to_response(template_name, { "album_list": album_list, })