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])
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 want to receive only the hour part or minute part in django. Right now i'm using remindTime = request.POST.get("remindTime") to get the time but I only want the hour or minute or day or month. How can I do that?
here is the model
class Reminder(models.Model):
remindTime = models.DateTimeField(auto_now_add=False, auto_now=False)
how I get the time
if request.method == "POST":
remindTime = request.POST.get("remindTime")
Ty!
First, convert your string object to Datetime object:
my_string = '2019-10-31'
# Create date object in given time format yyyy-mm-dd
my_date = datetime.strptime(my_string, "%Y-%m-%d")
print(my_date)
print('Type: ',type(my_date))
Output:
2019-10-31 00:00:00 Type:
Second, step get your hour and minute:
print('Month: ', my_date.month) # To Get month from date
print('Year: ', my_date.year) # To Get month from year
Output:
Month: 10 Year: 2019
i want to get year from birthday.
so i use self.birthday.year
but it make error.
how do i fix it?
best regards.
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_("Name of User"), blank=True, max_length=255) #이름
gender = models.CharField(max_length=1, choices=CHOICES_GENDER) # 성
birthday = models.DateField(null=True) #생일
def calculate_age(self):
import datetime
return int((datetime.date.year - self.birthday.year) +1)
age = property(calculate_age) #나이
Try this solution,
from datetime import date
class User(AbstractUser):
name = models.CharField(_("Name of User"), blank=True, max_length=255)
gender = models.CharField(max_length=1, choices=CHOICES_GENDER)
birthday = models.DateField(null=True)
#property
def calculate_age(self):
if self.birthday:
today = date.today()
return today.year - self.birthday.year - ((today.month, today.day) < (self.birthday.month, self.birthday.day))
return 0 # when "self.birthday" is "NULL"
The problem is that datetime.date.year does not exists. You can fetch the year of a date (or datetime) object with .year, and you can thus for example use today() or now().
Semantically the function is incorrect as well. If I am born in 1984, then I am not per se 35 years old: that depends on whether the current year is before or after the day of birth (for example February 9th).
Finally there can be an error if the self.birthday value is None. In that case you probably want to return None as well.
So a potential solution for this is:
from datetime import date
class User(AbstractUser):
# ...
def calculate_age(self):
bd = self.birthday
if bd:
td = date.today()
return td.year - bd.year - ((td.month, td.day) < (bd.month, bd.day))
We thus first calculate today(), and then we return the current year minus the year of the birthday and minus one if today is still before the birthday this year.
In case the user did not specify his/her birthday, then the calculate_age(..) will return None (a value that can be interpreted as "unknown").
An issue that still remains (and is harder to fix) are timezones: since today in Australia is another today than in the United States, it is possible that - depending on where the server and users are located - the age of a user is one too high the day before his/her birthday, or one too low one day on his/her birthday. This is a harder problem to solve, since we have no information here where the user is located.
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)
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()