我正在建立一个照片库,那些发布的照片库并没有给我我需要的东西,所以我正在构建它的形式。
在索引页面中,我需要从相册模型中获取随机相册(这很好),并且每张相册都要从照片模型中获取其中一张照片(random
)。
型号:
class Album(models.Model):
title = models.CharField('כותרת', max_length=100, db_index=True)
created = models.DateTimeField('תאריך פרסום', auto_now_add=True)
creator = models.ForeignKey(User, related_name='galleries_creator', verbose_name='נכתב ע"י')
class Photo(models.Model):
title = models.CharField('כותרת', max_length=100)
album = models.ForeignKey(Album, verbose_name='שייך לאלבום')
photo = models.ImageField('תמונה', blank=True, upload_to=get_image_path)
photo_mid = models.ImageField('תמונה בינונית', blank=True, upload_to='images/galleries/mid/', editable=False)
photo_thumb = models.ImageField('תמונה קטנה', blank=True, upload_to='images/galleries/thumbs/', editable=False)
created = models.DateTimeField('תאריך פרסום', auto_now_add=True)
is_landscape = models.NullBooleanField(blank=True, verbose_name='האם תמונת לנדסקייפ', editable=False)
就像我看到的那样,为了迭代模板中的相册并获得相册的正确照片,我需要链接相册列表和我得到的照片列表,但是正确的顺序(album object, photo object etc
),但我得到的是所有相册,然后是所有照片(按照正确的顺序,但在模板中没有任何工作,显而易见)。
查看:
def index(request):
albums = Album.objects.all().order_by('?')[:10]
album_photo_lst = []
for album in albums:
album_photo_lst.append(Photo.objects.filter(album=album).order_by('?')[:1])
album_list = list(chain(albums,album_photo_lst))
return render_to_response('galleries/index.html',{'albums':album_list}, context_instance=RequestContext(request))
也许我过于复杂了,也许有人可以帮我解决这个问题。
10倍, 埃雷兹
答案 0 :(得分:1)
如果没有尝试更改您的查询,我建议您使用(album, photo)
tuples列表而不是长列表:
for album in albums:
album_list.append((album, Photo.objects.filter(album=album).order_by('?')[0]))
现在使用
{{ for album, photo in album_list }}
(如果相册中有0张照片,请务必查看会发生什么。)