0

I have an album track model with a pre-defined Meta.ordering. In my debugger, I got bitten by something like this :

pdb> album.tracks.all()[0]
<Track: track 2>
ipdb> album.tracks.all() # WTF ?
[<Track: track 1>, <Track: track 2>]
ipdb> m = album.tracks.all()
ipdb> m[0]
<Track: track 2>
ipdb> m = list(album.tracks.all())
ipdb> m[0]
<Track: track 1>

Why does this happen ? Is there some best practices about this ?

0

1 Answer 1

1

Don't think the query set is ordered by default. Although it doesn't seem to be mentioned explicitly in the doc, but this can give some hint

On ordering and order_by()

Warning :

Ordering is not a free operation. Each field you add to the ordering incurs a cost to your database. Each foreign key you add will implicitly include all of its default orderings as well.

So if you have not specified any default ordering field, the queryset will not be ordered.

Sample:

>>> from myapp.models import *
>>> a=MyModel.objects.all()
>>> a.ordered
False
>>> b=MyModel.objects.all().order_by()
>>> b.ordered
False
>>> c=MyModel.objects.all().order_by('id')
>>> c.ordered
True
Sign up to request clarification or add additional context in comments.

3 Comments

+1 but I did setup Meta.ordering, so it SHOULD be ordered. Unfortunaly, I checked an queryset.ordered is False.
@e-satis, Have you set ordering for tracks? In my test I do get ordered==True when its set in Meta, even for ForeignKey relations (like user1.mymodel_set.all()).
I found my problem : I order tracks with the through model, and I should use order_with_respect_to

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.