[Django]-Django sort the query elements in a weekly monthly daily fashion

5πŸ‘

βœ…

In order to have access to test through Person Model you can define your own related_name such as tests or just use the default provide by django test_set:

class Test(models.Model):
    person = models.ForeignKey(Person, related_name='tests')
    date = models.DateTimeField(auto_now_add=True)
    test_name = models.CharField(max_length=200,default='',blank=False)
    subject = models.CharField(max_length=100,default='')

related_name define a reverse relation so you can do the following query:

  person_1.tests.all()
  person_1.tests.filter(date=date)
  person_1.tests.filter(date__day=day) # day is an integer
  person_1.tests.filter(date__month=month) # month is an integer

but there is no default support for week, but you still can do it using range feature:

import datetime
start_date = datetime.date(2015, 12, 16)
end_date = start_date + datetime.timedelta(days=7)
person_1.tests.filter(date__range=(start_date, end_date))

Example :

in views.py:

def get_current_month():
    now = datetime.now()
    return now.strftime("%m")

def get_current_year():
    now = datetime.now()
    return now.strftime("%y")

def tests_by_month(request, id):
    person = Person.objects.get(id=id)
    month = request.GET.get('month', get_current_month()) # if no month take the current as default
    year = request.GET.get('month', get_current_year()) # if no year take the current as default
    test_list = person.tests.filter(date__month=int(month), date__year=int(year))
    context = {'test_list': test_list}
    return render_to_response(request, 'template.html', context)

in urls.py :

url(r'^app/persons/(?P<id>\d+)/tests/', tests_by_month),

and you use the following url

app/persons/(?P<id>\d+)/tests/?month=12&year=2014

if you send without month: app/persons/(?P<id>\d+)/tests/ you will get the tests of the current month and current year

πŸ‘€Dhia

2πŸ‘

This is an addition to the answer above as it does not support years which means the tests data would not be accurate if the data accumulates over the years. For example if there is 2014 and 2015 January data, then getting the data by month would return both 2015 and 2014 january data.

Solution

Supply the year also in the request and filter using year in the model also

def tests_by_month(request, id):
    person = Person.objects.get(id=id)
    month = request.GET.get('month', get_current_month()) 
    year = request.GET.get('year', datetime.now().year)
    test_list = person.tests.filter(date__month=int(month),   date__year=year)
    context = {'test_list': test_list}
    return render_to_response(request, 'template.html', context)
πŸ‘€User Rik

Leave a comment