Reputation: 323
Accept my apologies I couldn't explain the question any better in the title.
I have a model like below:
class MyModel(models.Model):
created_time = models.DateTimeField(auto_now_add=True)
The objects can be created at any time and have that time saved in created_time.
I want to filter all the objects that are created from just before yesterday until now.
So if we consider that we are at 22:00 now, and we have 5 objects from yesterday 22:00 until now, I also want the last object that is created before yesterday 22:00, and it can be created a month ago.
The query below not work because it omits the last object before yesterday:
from datetime import timedelta, datetime
yesterday = datetime.today() - timedelta(days=1)
objs = MyModel.objects.filter(created_time__gte=yesterday)
Can anyone help me with this?
Upvotes: 1
Views: 143
Reputation: 3374
I think you would need to query the database twice.
counts = MyModel.objects.filter(created_time__gte=yesterday).count()
objs = MyModel.objects.order_by('-created_time')[:counts+1]
Upvotes: 2