Good idea, thank you! :-D
On May 8, 6:10 pm, Tim Chase <django.us...@tim.thechases.com> wrote:
> > First define some list contain random values such as:
>
> >>>> foo_list = (3, 4, 5, 2)
>
> > Then use QuerySet to query the list in a table, but it returns objects
> > will increase id value.
>
> >>>> foo = Foo.objects.filter(id__in = foo_list)
>
> > Actually result:
> >>>> print foo.values
> > [{'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}]
>
> > Expect result:
> >>>> print foo.values
> > [{'id': 3}, {'id': 4}, {'id': 5}, {'id': 2}]
>
> > I tried in mysql shell, it looks a mysql bug, but I hope django's ORM
> > have some workaround to resolve it.
>
> Unless you explicitly specify an ordering, the database can
> return the data in whatever order it likes (with no guarantees).
> Given that foo_list is not sorted, there's no way to force the
> database to return values in this order.
>
> If they have to be in the order of the IDs as found in the
> original list, you may be able to do it something like
>
> foo_as_dict = dict(
> (v.id, v)
> for v in foo.values
> )
> results = [
> foo_as_dict[id]
> for id in foo_list
> if id in foo_as_dict
> ]
>
> However, if the ordering of the source is truly *random*, then
> there's no reason to maintain that order if another truly random
> ordering can be provided:
>
> import random
> results = list(foo.values)
> random.shuffle(results)
>
> or even just
>
> foo = Foo.objects.filter(id__in = foo_list).order_by('?')
>
> as described here[1].
>
> -tim
>
> [1]http://www.djangoproject.com/documentation/models/ordering/
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to
django-users+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---