How to chain quesrysets in the right order not sorted by date, sorted by foreignKey?
I am building a photo gallery, and the ones that are published don't give me what i need so i am building it form scratch.
In the index page i need to get random albums (this is fine) from the Album model and for each album to bring one of its photos (random
) from the Photo model.
Models:
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 =开发者_如何学JAVA 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)
The thing is, as i see it, that in order to iterate over the albums in the template and get the correct photo for the album, i need to chain the list of albums and the list of photos i got, but in the right order (album object, photo object etc
), but what i am getting is all the albums and then all the photos (in the right order, but in the template nothing is working, obvious).
View:
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))
Maybe i am over complicating this, and maybe some one can help me get thru this.
10x, Erez
Without tryiung to change your queries, I suggest to use a list of (album, photo)
tuples instead of a long list:
for album in albums:
album_list.append((album, Photo.objects.filter(album=album).order_by('?')[0]))
now use
{{ for album, photo in album_list }}
(And be sure to check what happens if there are 0 photos in the album.)
精彩评论