[Django] #33531: Random ORDER BY not working with MSSQL

7 views
Skip to first unread message

Django

unread,
Feb 21, 2022, 7:30:20 AM2/21/22
to django-...@googlegroups.com
#33531: Random ORDER BY not working with MSSQL
-------------------------------------+-------------------------------------
Reporter: coronoro | Owner: nobody
Type: Bug | Status: new
Component: Database | Version: 3.0
layer (models, ORM) |
Severity: Normal | Keywords:
Triage Stage: | Has patch: 0
Unreviewed |
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-------------------------------------+-------------------------------------
Given a simple Model:

{{{
class Person(models.Model):
name = models.CharField(max_length=100)
country_code = models.CharField(max_length=3, blank=True, null=True)

class Meta:
db_table = 'persons'
}}}

I want to pick an entry randomly by using

{{{
Person.objects.all().order_by('?')
}}}

the resulting query has the following order by clause

{{{
... FROM [persons] ORDER BY RAND() ASC
}}}

This however does not give a randomized order of the table. Instead it
always returns the same entries in the same order(ordered by id).

The desired result can be achieved with
{{{
... ORDER BY NEWID()
}}}

I am aware that this also isn't an exactly optimal solution as stated
here: [https://dba.stackexchange.com/questions/955/what-is-the-best-way-
to-get-a-random-ordering].


For completeness: I observed this behaviour using a MSSQL14 Server

--
Ticket URL: <https://code.djangoproject.com/ticket/33531>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

Django

unread,
Feb 21, 2022, 7:43:52 AM2/21/22
to django-...@googlegroups.com
#33531: Random ORDER BY not working with MSSQL
-------------------------------------+-------------------------------------
Reporter: coronoro | Owner: nobody
Type: Bug | Status: closed
Component: Database layer | Version: 3.0
(models, ORM) |
Severity: Normal | Resolution: invalid
Keywords: | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0

Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Changes (by Mariusz Felisiak):

* status: new => closed
* resolution: => invalid


Comment:

Thanks for this report, however Django 3.0 is not supported anymore and
the backend for MSSQL is not built-in. You should report this issue on a
bug tracker for the 3rd database backend you're using.

--
Ticket URL: <https://code.djangoproject.com/ticket/33531#comment:1>

Reply all
Reply to author
Forward
0 new messages