尝试创建一个对象的元组创建一个对象和一个查询 [英] Trying to create a tuple of objects create an object and a queryset

查看:161
本文介绍了尝试创建一个对象的元组创建一个对象和一个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历模板中的一个元组,但是从我建立的代码中我得到一个对象(专辑)和一个查询(照片)的元组。问题是我们现在在模板中如何迭代?

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?

模型:

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)

查看:

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

模板:

{% 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.creator.first_name }} {{ album.creator.last_name }}</p>
    </div>
{% endfor %}

正如我所见,我无法做照片。照片因为照片是一个列表,而不是一个对象,我真的不想为元组中的每张照片做一个for循环(只有一张照片,所以这只是一个浪费)。

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返回:

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?

推荐答案

如果每张专辑只有一张照片,那么为什么要切割queryset?只需使用索引获得第一个:

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

这篇关于尝试创建一个对象的元组创建一个对象和一个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆