我收到了一份人员名单以及他们在同一个项目中从api中获得的测试.我希望用户可以选择查看城市中有三个选项的测试次数 - 每日/每周/每月.
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='')
每个城市的人们的json文件就像http://pastebin.com/pYLBjrjh一样生成
有关 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)
这将生成该城市中已经参加测试的名称列表.我想知道是否有办法让用户选择时间段(每日/每周/每月),并且只查看在该时间段内参加测试的名称.
为了有机会通过角色模型来测试您可以定义自己的related_name如tests
或只使用默认的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定义反向关系,以便您可以执行以下查询:
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
但是周没有默认支持,但你仍然可以使用范围功能:
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))
示例:
在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)
在urls.py中:
url(r'^app/persons/(?P\d+)/tests/', tests_by_month),
并使用以下网址
app/persons/(?P\d+)/tests/?month=12&year=2014
如果您没有月份发送:app/persons/(?P
您将获得当前月份和当前年份的测试