I have a calendar model that records the number of contributions users make per day:
class CalModel(db.Model):
user = db.ReferenceProperty(UserModel, collection_name = "calendar")
date = db.DateTimeProperty(auto_now_add = True)
contrib = db.IntegerProperty(required = True)
I want to query for the CalModel entity whose date attribute is yesterday. How do I specify a datetime object that whose day is yesterday? (The strftime format is the default)
Something that goes like:
cal = CalModel.all().filter("date", DATETIMEOBJECT).get()
Figured it out.
yesterday = datetime.today() - timedelta(1)
query = CalModel.all().ancestor(calendar_key()).filter("user", user).filter("date", yesterday).get()
Related
models.py
class Dibbs_Fields(models.Model):
hash = models.CharField(max_length=16)
nsn = models.CharField(max_length=32)
nomenclature = models.TextField()
technical_documents = models.TextField()
return_by = models.DateField()
How to filter this class in django views according to the date return_by ? I don't want to show the data that is expired i.e. if the return_by date is earlier than today's date, then it should not show.
You can do this:
from datetime import date
def func(request):
today = date.today()
data = Dibbs_Fields.objects.filter(
return_by__lt=today)
The code simply returns data are earlier than today's date.
EDIT
return_by__lt # less than
return_by__gt # greater than
return_by__gte # greater than or equal to
return_by__lte # less than or equal to
I have a django model like this
class AthleteSubscription(models.Model):
user = models.ForeignKey(User, related_name="user_subscription", default='')
subscription_start = models.DateField(default=datetime.date.today)
subscription_end = models.DateField(default=datetime.date.today() + timedelta(30))
Where subscription_start is start date of subscription and subscription_end is the end date of subscription. Subscription is of 30 days. I want to get those records in which current date (date today) lies between subscription_start and subscription_end. How can I do this with django ORM.
qv = AthleteSubscription.objects.filter(subscription_start__gte=some_date, subscription_end__lte=some_date)
Extending from the question here, where queryset is filtered using input from the user, I wanted to know if it was possible to filter queryset depending on present month and week. Eg each month should start on the 1st and each week on a monday and the queryset should be filtered for all the tests that have taken place in the present month and week.
models.py
class City(models.Model):
city_name=models.CharField(max_length=100,default='',blank=False)
class Person(models.Model):
title = models.CharField(max_length=3,default="mr",blank=False)
name = models.CharField(max_length=50,default='',blank=False)
address = models.CharField(max_length=200,default='',blank=False)
city = models.ForeignKey(City)
class Test(models.Model):
person = models.ForeignKey(Person)
date = models.DateTimeField(auto_now_add=True)
test_name = models.CharField(max_length=200,default='',blank=False)
subject = models.CharField(max_length=100,default='')
views.py
def personlist(request, id):
data = requests.get('http://127.0.0.1:8000/app/cities/' + id + '/persons/').json()
context = RequestContext(request, {
'persons': data['results'],'count': data['count'],
})
return render_to_response('template.html', context)
And the related json
According to this question - one way could be to use
startdate = date.today()
enddate = startdate + timedelta(days=6)
Sample.objects.filter(date__range=[startdate, enddate])
But wouldn't date.today() keep changing everyday and thus everyday a new week will start and thus, a new queryset?Similarly with month. Is there a way to get querysets filtered by present week and month. With each starting from every monday and every 1st respectively?
You can use the __month and __year lookups to limit the queryset to this month's objects.
from datetime import date
today = date.today()
this_month_qs = Sample.objects.filter(
date__month=today.month,
date_year=today.year,
)
To find this weeks objects, you first need to find the date of this Monday. You can do this by finding today's day of the week (Monday = 0, Sunday = 6) using a date's weekday() method, and subtracting that many days from today. It's easy to calculate the last day of the week by adding 6 days, and then you can use __range to find this week's objects.
from datetime import date, timedelta
today = date.today()
# Use today.isoweekday() if you want the week
# to start on Sunday instead of Monday
first_day_of_week = date.today() - timedelta(today.weekday())
end_date = first_day_of_week + timedelta(days=6)
this_week_qs = Sample.objects.filter(date__range=[startdate, enddate])
It seems to be easy but it creates confusion for me. My code is
today = datetime.datetime.now()
StatusObj = Status.objects.filter(taskPeople__people__email = useremail,dateCreated__year = today.year, dateCreated__month = today.month, dateCreated__day = today.day)
it is expected that it will filter the query whose date is today. But it doesn't filter instead it filter one day back query.
when I do.
today.day
>> 20
Status.objects.filter(taskPeople__people__email = useremail,dateCreated__year = today.year, dateCreated__month = today.month, dateCreated__day = today.day)[0].dateCreated.day
>>19
You should use django.utils.timezone.now instead of datetime.datetime.now.
from django.utils import timezone
today = timezone.now()
...
Read the question #3 in the troubleshooting section of the timezones docs.
Have looked through DateField, TimeField, DateTimeField related documents but I cannot seem to find what I need. I simply want to have a selection of month, day, year, hour, minute, (AM/PM) type option. I have tried using 'choice=', but do not get the nice behavior I am looking for.
** TL;DR: I simply want a way of putting in the date and time without having to type it in. I would like a nice drop down menu **
class Event(models.Model):
event_name = models.CharField(max_length = 50)
date_time = models.DateTimeField()
date = models.DateField()
location = models.CharField(max_length = 30)
address = models.CharField(max_length = 30)
city = models.CharField(max_length = 30)
zip_code = models.CharField(max_length = 30)
state = models.CharField(max_length = 30)
description = models.TextField()
def __unicode__(self):
return self.event_name
class EventForm(ModelForm):
class Meta:
model = Event
This is what I currently have. I have removed the choices part and I even tried making my own model object dedicated to date and time, but that did not go well
I tried it using this ...
DATE_CHOICES = (('Jan', "January"),
('Feb', "Feburary"),
('Mar', 'March'),
('Apr','April'),
('May ','May'),
('June','June'),
('July','July'),
('Aug','August'),
('Sept','Septemeber'),
('Oct','October'),
('Nov','November'),
('Dec','December')
)
class DateTime(models.Model):
month = models.CharField(max_length = 5, choices=DATE_CHOICES)
But I am not getting the correct behavior as I want.
You might be interested in using jquery date picker or jquery datetime picker.
http://jqueryui.com/datepicker/
http://trentrichardson.com/examples/timepicker/
On both sites there are exampels so you can see it in action :)
You definitely want to use this snippet. Unless you're a django ninja and want to roll up your own multi widget, which is what you will need to transform a set of select inputs into one datetime value.
This widget is the closest you will get to do it, without using any js plugins.
Your can use datepicker plagin as Erfin mentioned (I recommend it too and also datepicker for bootstrap) for date and masked input for time or just simple selects. Anyway you should send a request with datetime information. What to do in django:
If you use datepicker plugin for date and masked input for time
Let's assume that your request is POST. Your date will be a string with format you specify in javascript. It looks like "31.01.2013". And time will be like "22:30".
def write_datetime(request):
event = Event.objects.get(id=int(request.POST.get('id')))
from datetime.datetime import strptime
date = request.POST.get('date')
time = request.POST.get('time')
date_time = date + " " + time
event.date_time = strptime(date_time, "%d.%m.%y %H:%M"
event.save()
If you use just selects
In this case, it's simplier to make a datetime string from request parameters and repeat the preveous example.
def def write_datetime(request):
year = request.POST.get('year')
month = request.POST.get('month')
# etc
date_time = "%s.%s.%s %s:%s" % (day, month, year, hours, minutes)
# etc