I am getting a list of people and the tests they have taken from an api in the same project. I would like the user to have an option to see the number of tests that have taken place in a city with three options - daily/weekly/monthly.
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='')
The json file for people in each city is generated like this http://pastebin.com/pYLBjrjh
related 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)
This generates the list of names in that city that have taken the test. I want to know if there is a way to let the user select the time period.(daily/weekly/monthly) and only view the names that have taken the test in that time period.
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 djangotest_set
:related_name define a reverse relation so you can do the following query:
but there is no default support for week, but you still can do it using range feature:
Example :
in views.py:
in urls.py :
and you use the following url
if you send without month:
app/persons/(?P<id>\d+)/tests/
you will get the tests of the current month and current yearThis 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