Skip to content

Commit

Permalink
feat: Add support for randomized ordering of fakequeryset (#187)
Browse files Browse the repository at this point in the history
Fixes #111
  • Loading branch information
KIRA009 authored and gasman committed Feb 23, 2024
1 parent 8bf0faf commit df4c6be
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Changelog
6.3 (xx.xx.xxxx)
~~~~~~~~~~~~~~~~
* Support filtering with Q objects (Shohan Dutta Roy)
* Support random ordering with `.order_by("?")` (Shohan Dutta Roy)
* Fix: Correctly handle filtering on fields on related models when those fields have names that match a lookup type (Andy Babic)
* Fix: Correctly handle null foreign keys when traversing related fields (Andy Babic)

Expand Down
5 changes: 5 additions & 0 deletions modelcluster/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from functools import lru_cache
from django.core.exceptions import FieldDoesNotExist
from django.db.models import ManyToManyField, ManyToManyRel, Model
import random

REL_DELIMETER = "__"

Expand Down Expand Up @@ -154,6 +155,10 @@ def sort_by_fields(items, fields):
# To get the desired behaviour, we need to order by keys in reverse order
# See: https://docs.python.org/2/howto/sorting.html#sort-stability-and-complex-sorts
for key in reversed(fields):
if key == '?':
random.shuffle(items)
continue

# Check if this key has been reversed
reverse = False
if key[0] == '-':
Expand Down
14 changes: 14 additions & 0 deletions tests/tests/test_cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -780,6 +780,20 @@ def test_ordering_accross_foreignkeys(self):
)
)

def test_random_ordering(self):
beatles = Band(name='The Beatles', members=[
BandMember(name='John Lennon'),
BandMember(name='Paul McCartney'),
BandMember(name='George Harrison'),
BandMember(name='Ringo Starr'),
])

# Check that all members are returned
self.assertCountEqual(
beatles.members.order_by('?'),
[beatles.members.get(name=name) for name in ['John Lennon', 'Paul McCartney', 'George Harrison', 'Ringo Starr']]
)

def test_filtering_via_manytomany_raises_exception(self):
bay_window = Feature.objects.create(name="Bay window", desirability=6)
underfloor_heating = Feature.objects.create(name="Underfloor heading", desirability=10)
Expand Down

0 comments on commit df4c6be

Please sign in to comment.