在Django视图中,order_by()不适用于filter() [英] order_by() doesn't work with filter() in Django view

查看:186
本文介绍了在Django视图中,order_by()不适用于filter()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型:

...
class Bild(models.Model):
    album = models.ForeignKey(Album)
    slot = models.IntegerField()
    bild = models.ImageField(upload_to='bilder', null=True)
    untertitel = models.CharField(max_length=200, null=True)
    def __unicode__(self):

我的观点: p>

My view:

def album_bild(request, album_id, bild_id):
    album_id = int(album_id)
    bilder = Bild.objects.filter(album__id = album_id).order_by('slot')
    ....

当我在模板中迭代bilder时,我可以看到filter()有效,但是对象仍然由pk而不是slot排序。

When I iterate through "bilder" in the template, I can see that the filter() did work but the objects are still ordered by the pk instead of the "slot".

我使用filter()和order_by()是否有问题?

Is there a problem with my usage of filter() and order_by()?

编辑:我想我应该添加一切在shell中正常工作。那么也许错误在模板中??

I guess i should add that everything works fine in the shell. So maybe the error is in the template...?

{% for bild in bilder %}
    <li 
    {% ifequal bild.slot bild_id %}
            class="active" 
    {% endifequal %}
    onclick="window.location.href='/portfolio/{{ album_id }}/{{ bild.slot }}'"><div>{{ bild.slot }}</div></li>
{% endfor %}

{% for i in empties %}
    <li class="empty"></li>
{% endfor %}


推荐答案

已经做了很多 .filter()。order_by()链,就像你在那里一样,没有任何东西跳到我身边。我从来没有试图把这个顺序传递给模板,而不用进一步处理对象(通常是遍历它们),所以我不知道$ code> order_by()是否丢失django的懒惰评估的一部分?也许尝试在 list()中包装 filter()。order_by()被推迟到稍后的时间?

I've done lots of .filter().order_by() chains just as you have them there, and nothing jumps out to me as out of place. I've never tried to carry that ordering over to the template without further processing the objects though (usually iterate over them), so I wonder if the order_by() is lost as part of django's lazy evaluation? Maybe try wrapping the filter().order_by() line in a list() to force evaluation there instead of it being put off till some later time?

bilder = list(Bild.objects.filter(album__id = album_id).order_by('slot'))

这是黑暗中的一个镜头,但足够快,值得一试。

It is a shot in the dark, but quick enough to be worth a try.

这篇关于在Django视图中,order_by()不适用于filter()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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