Home > Blockchain >  first and last methods used excluded items
first and last methods used excluded items

Time:12-22

i used last() to get last item of queryset after exclude some items as below:

holidays = HolidayModel.objects.all().values_list('date', flat=True)
result = BorseExchangeLog.objects.exclude(
hint_time__date__in=holidays
)
# output 1
print(list(result.valuse_list('hint_time__date',flat=True).distinct('hint_time__date')))
#output2
print(result.last().hint_time.date())

but in output2 print item that not exists in output1

i test some other codes as below:

print(list(logs.values_list('hint_time__date',flat=True).distinct('hint_time__date')))
print(list(logs.values_list('hint_time__date', flat=True).distinct('hint_time__date'))[-1])
print(logs.order_by('hint_time__date').last().hint_time.date())


[..., datetime.date(2020, 10, 21), datetime.date(2020, 10, 26)]
2020-10-26
2020-10-25

my holiday model:

class HolidayModel(models.Model):
    creator = models.ForeignKey('accounts.Account', on_delete=models.PROTECT, verbose_name=_('Creator'))
    reason = models.CharField(default='', max_length=200, verbose_name=_('Reason'))
    date = models.DateField(default=timezone.now, verbose_name=_('Date'))

and other model is :

class BorseExchangeLog(models.Model):
    create_time = models.DateTimeField(default=timezone.now)
    hint_time = models.DateTimeField(default=timezone.now)

i test that by first() and problem was there too

what is problem? my code is wrong or bug from django orm?

using django2.2 and postgresql

CodePudding user response:

Your datetimes are timezone aware but the date() method on datetime objects does not take the timezone into account, __date will take the timezone into account provided your DB supports it. Use the django.utils.timezone.localdate function to get a date taking into account the timezone

from django.utils.timezone import localdate
print(localdate(result.last().hint_time))
  • Related