Reputation: 103
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 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')
....
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".
Is there a problem with my usage of filter() and order_by()?
EDIT: 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 %}
Upvotes: 10
Views: 22540
Reputation: 101
If you too are using Django Rest Framework, I ended up here searching for why .order_by() was not working when applied to a queryset in my ModelView regardless of .filter() being present or not.
If you don't need to define your own get_queryset, don't! The django-filters library solved this issue for me replacing my conditional get_queryset function into 3 lines just using the OrderFilter.
Original answer that helped me
Upvotes: 1
Reputation: 61
In your views.py You need not use
filter(album__id = album_id)
(with double underscores) since 'Album' is not related as a ManyToManyField
here 'Album' is just a ForeignKey
so the views.py should have
def album_bild(request, album_id, bild_id):
album_id_local = int(album_id)
bilder = Bild.objects.filter(album_id=album_id_local).order_by('slot')
....
(with a single underscore).
reference to django doc: https://docs.djangoproject.com/en/2.0/topics/db/queries/#lookups-that-span-relationships
Upvotes: 0
Reputation: 506
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.
Upvotes: 16
Reputation: 129
You should try to order by slot__id.
Like this:
bilder = Bild.objects.filter(album__id = album_id).order_by('slot__id')
Upvotes: 5