How to filter by timezone.localdate()

I’ve been trying to filter objects in my page by the date they were added, unfortunately I had no success. Maybe the right question is how to iterate over these dates

Models:

class Day(models.Model):
name = models.CharField(max_length=255, default=timezone.localdate(), blank=True)
def str(self):
return self.name

class Sale(models.Model):
value = models.CharField(max_length=25, editable=True, default=‘’)
date_time = models.DateField(default=timezone.now,)
name = models.CharField(max_length=127, editable=True, blank=True, default=‘’)
day = models.ForeignKey(Day, on_delete=models.DO_NOTHING, default=‘’, blank=True)
def str(self):
return self.value


views function

def day_details(request, day_id):
day = get_object_or_404(Day, id=day_id)

sales = Sale.objects.order_by('-id').filter(
    Day.name   <====
)
return render(request, 'home/day_details.html', {
    'day': day,
    'sales': sales
})

I tried converting the values to str, using their id, all I want is to filter them by the same date they were added


cannot unpack non-iterable ForwardManyToOneDescriptor object
cannot unpack non-iterable int object
cannot unpack non-iterable DeferredAttribute object

One option that works for me is to add the meta class to your model class, this will order a queryset by the ordering in the Meta:

class Sale(models.Model):
	value = models.CharField(max_length=25, editable=True, default=’’)
	date_time = models.DateField(default=timezone.now,)
	name = models.CharField(max_length=127, editable=True, blank=True, default=’’)
	day = models.ForeignKey(Day, on_delete=models.DO_NOTHING, default=’’, blank=True)
	def str(self):
	return self.value
	
	class Meta:
	   ordering = ['-date_time']

Edit

Sorry I just realised I didn’t answer your question about ordering by local time. But also the way I add the date in the model is like this:

date_time = models.DateTimeField(auto_now_add=True)

Not sure if that makes a difference for you.

Then in your view do:

sales = Sale.objects.all()

Then put sales into your context and it will be sorted by newest first.