Order_by () does not work with filter () in Django view

My model:

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

My opinion:

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

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

Is there a problem with using filter () and order_by ()?

EDIT: I think I should add that everything works fine in the shell. Perhaps a mistake 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 %} 
+6
source share
2 answers

I made a lot of chains .filter().order_by() just like you have there, and nothing jumps because of me as inappropriate. I never tried to transfer this order to a template without further processing of objects (usually iterating over them), so I wonder if order_by() will lose as part of a lazy django evaluation? Maybe try wrapping the string filter().order_by() in list() to force an evaluation there, instead of deferring it to a later time?

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

It's a shot in the dark, but fast enough to be worth a try.

+11
source

You should try to order the slot__id file.

Like this:

 bilder = Bild.objects.filter(album__id = album_id).order_by('slot__id') 
+2
source

Source: https://habr.com/ru/post/888942/


All Articles