django : Model filter on date ranges - django

How to get model filter on date ranges.
In my project using employee doj, i need to deign a table.
like employee who have joined less than three months , 3-6month, 6-12 months, 12-24 months.
Depart < 3month 3-6months 6-12months 12-24months
----------------------------------------- ---- -----
A dep 4 6 6 8
------------------------------------------------------
How to do this filter in django.
I have gone through this link ,but its confusing .
http://www.nerdydork.com/django-filter-model-on-date-range.html
Thanks in Advance

The range filter works like this:
MyModel.objects.filter(date__range=(range_start, range_end))
You can use that in conjunction with datetime.timedelta to get month periods. For example:
from datetime import datetime, timedelta
now = datetime.now()
# <3 months
three_months_ago = now - timedelta(months=3)
MyModel.objects.filter(date__range=(three_months_ago, now))

Related

How to sort , filter and display model data using week number in django

I would like to sort my model's data on a week number for example when user logins user will see current week number and associated data and user should be able to select previous week number and get all past data as well also week starts on Sunday and ends on Saturday (considering 1 week)
Select Week :[2021 - 30 ] <- week number
You can filter it such way:
from datetime import datetime, timedelta
itemsList = Model_Name.objects.filter(user=request.user, created_date__gte=datetime.now()-timedelta(days=7))
I have got similar problem in my task and I solved it in simple steps:
#django #django-models #django-views #problem-solving
def get_weeks(request):
week = now().isocalendar()
if Event.objects.filter(start_date__week=week.week).exists():
instances=Event.objects.filter(start_date__week=week.week)

Rolling 12 months regardless of year in Django

How would I go about setting up a rolling 12 month period in Django without any year.
I am trying to plot the academic year but the problem I am finding mainly due to my lack of knowledge is that I have to set the year in datetime
I would like to try and create a start and end date for the academic year which runs from the beginning of April to the end of March every year however I have to include the year in all the objects such as datetime.
Is there a way for me to set a start and end date regardless of the year, the only way I can think of so far is to take the end of March as a start date and then count 12 months from then.
As always, thank you for the help.
timedelta might be help full. check out documentation
import datetime
start_date = datetime.datetime.now()
end_date = start_date + datetime.timedelta(days=365)

How to add a day to a year,month,day datetime object

I found similar posts but had issues with them.
The problem I have is:
I have a date in the format year, month, day example - 2019:01:21
and I want to use a loop likely something like
for i in range(365):
# add to the date by a single day and return something in the form 2019:01:22
You could use datetime.strptime() to parse the given date in string format to a python date format. Then you could use datetime.timedelta() to specify an interval of n days and shift the parsed date by this delta. Here is a short demo:
from datetime import datetime, timedelta
date = datetime.strptime("2019:01:21", "%Y:%m:%d")
for i in range(365):
delta = timedelta(days=1 + i)
print(date + delta)
Output:
2019-01-22 00:00:00
2019-01-23 00:00:00
2019-01-24 00:00:00
...

django aggregate sum of subgroup maximums

I have the following simplified setup in Django, using MySQL:
class Category(models.Model):
name = models.CharField(max_length=255)
class MyTable(models.Model):
category = models.ForeignKey('Category', on_delete=models.CASCADE)
date = models.DateField()
amount = models.IntegerField()
class Meta:
unique_together = ['category', 'date']
And a query set comprised of the following sample data for MyTable:
date category_id amount
2017-12-01 3 2
2018-01-01 1 100
2018-02-01 1 50
2018-03-01 2 2000
2018-04-01 2 4000
2018-05-01 3 2
2018-06-01 3 1
What I ultimately want is a way to get the sum of the amounts corresponding to the latest date for each category. To illustrate:
The latest date for category_id 1 is 2018-02-01, where the amount is 50;
The latest date for category_id 2 is 2018-04-01, where the amount is 4000;
The latest date for category_id 3 is 2018-06-01, where the amount is 1;
50 + 4000 + 1 = 4051
I'm trying to figure how to get the value 4051 through an aggregate call to this queryset. I've tried every combination of "values", "annotate" and "aggregate" I could think of and nothing gets the desired result. The following gets me the latest date for each category, but every time I try to get the sum of the corresponding amounts, it calculates it on every amount instead of just the maximums.
MyTable.objects.values('category').annotate(Max('date'))
Is what I'm trying to do possible through Django's ORM? I posted another question about what the MySQL syntax would be for this exact example, but can't get that to apply to a Django query set either.
Any guidance appreciated.
i think you need some data structures to achieve this please take a look at the below answer this if Djnago ORM or sql does not meet your requirement(unable to write)
l=[]
x=MyTable.objects.values('category').annotate(date=Max('date'))
for y in x:
qq= MyTable.objects.get(category_id=y.get(category),date=y.get(date))
l=l+qq.amount
total_amount = sum(l)
print(total_amount)

How do I filter a queryset to dates within the next x months?

I have a model called Post with an attribute date.
I want to filter the queryset so that I retrieve posts only in the next x months. e.g. next 3 months
from datetime import datetime
import calendar
def add_months(sourcedate, months):
month = sourcedate.month - 1 + months
year = sourcedate.year + month / 12
month = month % 12 + 1
day = min(sourcedate.day, calendar.monthrange(year,month)[1])
return datetime.date(year, month, day)
today = datetime.today()
table_name.objects.filter(date__range=[str(today.date()), str(add_months(today, 3).date())])
Reference
- How to increment datetime by custom months in python without using library
- Django database query: How to filter objects by date range?
Take a look at range. Build the date and pass to the QuerySet. Relevant SO question for reference.