开发者

Trying to create a tuple of objects create an object and a queryset

I need to iterate through a tuple in the template, but from the code i've built i am getting a tuple of an object (album) and a queryset (photo). The problem is how do i iterate over them now in the template?

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 = 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)

View:

def index(request):
    albums = Album.objects.all().order_by('?')[:10]
    album_list = []
    for album in albums:
        album_list.append((album, Photo.objects.filter(album=album).order_by('?')[:1]))
    return render_to_response('galleries/index.html',{'albums':album_list},  context_instance=RequestContext(request))

template:

{% for album, photo in albums %}
    <div class="polaroid" id="picture_{{ forloop.counter }}">
        <img src="{{ MEDIA_URL }}{{ photo.photo }}" alt="Picture #{{ forloop.counter }}" />
        <p class="caption"><p class="title">אלבום {{ forloop.counter }}</p><p>{{ album.c开发者_如何学编程reator.first_name }} {{ album.creator.last_name }}</p>
    </div>
{% endfor %}

As i see it, i can't do photo.photo because photo is a list, not an object and i really don't want to do a for loop for every photo in the tuple (there is only one photo, so this is just a waste).

assert False album_list returns:

[(<Album: אלבום שני - ממשק מנהל>, [<Photo: אלבום 2 תמונה 2>]), (<Album: אלבום ראשון - ממשק מנהל>, [<Photo: אלבום 1 תמונה 7>]), (<Album: אלבום  נתן>, [<Photo: נסיון 4>])]

What can i do in my view or template to solve this?


If there's only one photo per album you are after, then why slice the queryset? Just get the first one using index:

album_list.append((album, Photo.objects.filter(album=album).order_by('?')[0]))


Well, for now, using the inner for loop to solve this, And it is obviously working, but i will be happy to hear of any other suggestion to do it in a more efficient way if possible...

<img src="{% for p in photo %}{{ MEDIA_URL }}{{ p.photo }}{% endfor %}" alt="Picture #{{ forloop.counter }}" />

10x :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜