Opened 6 months ago

Closed 6 months ago

#30901 closed Bug (invalid)

first() and last() return same object (first in both cases) when the order_by field is the same

Reported by: Tadas Owned by: nobody
Component: Uncategorized Version: 2.2
Severity: Normal Keywords:
Cc: Tadas Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

from django.db import models
from django.utils import timezone

class TestModel(models.Model):
    name = models.IntegerField()
    created = models.DateTimeField()


dt = timezone.now()
for i in range(5):
    TestModel(
        name=str(i),
        created=dt
    ).save()

obj = TestModel.objects.all().order_by('created')

print(obj.first().name)
print(obj.last().name)

Both print statements above will print 0

Change History (2)

comment:1 Changed 6 months ago by Tadas

Cc: Tadas added
Type: UncategorizedBug

comment:2 Changed 6 months ago by Simon Charette

Resolution: invalid
Status: newclosed

Ordering on a non-unique field is undefined.

Since all your TestModel share the same created both ORDER BY created_at LIMIT 1 and ORDER BY created_at DESC LIMIT 1 can return the same value. This is just how your database backend decides to return it.

Note: See TracTickets for help on using tickets.
Back to Top