Reputation: 123
I'm not really experienced in Django, but now I am trying to develop simple project with model class like this:
class FacebookEvent(models.Model):
start_time = models.DateTimeField(null=True)
end_time = models.DateTimeField(null=True)
In view file - there's no problem when I want to get all objects where start_time is today, tomorrow or in any other date range (including hours):
my_date= request.POST.get('my_date','') # for eg. 2015-10-26
events = FacebookEvent.objects.all().filter(start_time__range=
(datetime.combine(my_date,(datetime.min).time()), datetime.combine(my_date,(datetime.max).time()))).order_by('start_time')
but now i have to check if requested date (my_date) is between start_time and end_time from model. I just have to do the same what I was doing before, but a little bit inversely...
It took me few hours, but still I can't find any concept how to solve this problem. Anybody have any idea?
Thanks in advance.
Upvotes: 6
Views: 8837
Reputation: 351
Slightly late to the party here, but if you're planning to use this range
feature frequently, I highly recommend checking out the new postgres range fields. They have a lot of handy query filters right off the bat and provide a much cleaner, intuitive way to deal with ranges.
Upvotes: 0
Reputation: 1462
Im not sure if I understand the question.
If you have a model instance and a date:
First you need to convert your date to a datetime.datetime object
from dateutil.parser import parse
my_date= request.POST.get('my_date','')
mdate = parse(mydate)
Then you can use mdate to do logical comparisons. i.e: mdate > fbEvent.start_time
If you want model instances between dates
mdate = parse(mydate)
events = FacebookEvent.objects.filter(start_time__gt=mdate, end_time__lt=mdate)
Upvotes: 4
Reputation: 5475
you can do like:
from datetime import datetime
my_date= request.POST.get('my_date','') # for eg. 2015-10-26
my_date = datetime.strptime(my_date, "%Y-%m-%d")
events = FacebookEvent.objects.filter(start_time__lt=my_date, end_time__gt=my_date).order_by('start_time')
Upvotes: 3
Reputation: 34677
The following should help you get started:
# assuming Sample is your model class and sampledate is your column to filter on
samples = Sample.objects.filter(sampledate__gt=datetime.date(2011, 1, 1), sampledate__lt=datetime.date(2011, 1, 31))
Upvotes: 0