Opened 5 years ago

Closed 5 years 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 by Tadas, 5 years ago

Cc: Tadas added
Type: UncategorizedBug

comment:2 by Simon Charette, 5 years ago

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