【发布时间】:2011-09-22 23:47:36
【问题描述】:
我正在建立一个照片库,但已发布的那些没有给我我需要的东西,所以我从头开始构建它。
在索引页面中,我需要从相册模型中获取随机相册(这很好),并为每个相册从照片模型中获取其中一张照片 (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 倍, 埃雷兹
【问题讨论】:
标签: python django django-models django-templates django-queryset