I am building a survey website using Django 1.7.7 and Python 3.4.4, where a user enters say his "name" and "id". I have a sql table called "list" that stores all the users names and id's. I would like my Django website to check if when a user enters his/her name and id, if the id already exists in the table for the past 30 days. Basically if the user's id exists in the past 30 days, he/she will not be prompted to take the survey, else they would have to take the survey.
我正在使用Django 1.7.7和Python 3.4.4构建一个调查网站,用户在其中输入“姓名”和“id”。我有一个名为“list”的sql表,它存储所有用户名和id。我希望我的Django网站在用户输入他/她的名字和id时,如果在过去的30天内已经存在该id。如果用户的id在过去30天内存在,基本上不会提示用户进行调查,否则必须进行调查。
I know I have to build a view function that checks this condition but I am unable to figure out what the query/logic should be. Any help on the view function would help me out in my development immensely! Thank you.
我知道我必须构建一个视图函数来检查这个条件,但是我不知道查询/逻辑应该是什么。视图功能的任何帮助都将极大地帮助我的开发!谢谢你!
1 个解决方案
#1
1
You can add "timestamp" field to your List model. You can even make Django automatically set it to now()
using auto_now_add
parameter
您可以向列表模型添加“时间戳”字段。您甚至可以使用auto_now_add参数使Django自动将它设置为now()
timestamp = models.DateTimeField(auto_now_add=True)
Than you can check if there are records with the same name and id within last month:
,以便你在上月内查询是否有相同姓名及身分的纪录:
from django.utils.timezone import now
import datetime
is_duplicate = List.objects.filter(id=id, name=name, timestamp__gte = now() - datetime.timedelta(days=30))
Note usages of __gte construtions - it means "greater than", and can be used with numbers and timestamps. This filter will only return records created within past 30 days. Hope this helps!
注意__gte解释的用法——它的意思是“大于”,可以与数字和时间戳一起使用。这个过滤器将只返回在过去30天内创建的记录。希望这可以帮助!
#1
1
You can add "timestamp" field to your List model. You can even make Django automatically set it to now()
using auto_now_add
parameter
您可以向列表模型添加“时间戳”字段。您甚至可以使用auto_now_add参数使Django自动将它设置为now()
timestamp = models.DateTimeField(auto_now_add=True)
Than you can check if there are records with the same name and id within last month:
,以便你在上月内查询是否有相同姓名及身分的纪录:
from django.utils.timezone import now
import datetime
is_duplicate = List.objects.filter(id=id, name=name, timestamp__gte = now() - datetime.timedelta(days=30))
Note usages of __gte construtions - it means "greater than", and can be used with numbers and timestamps. This filter will only return records created within past 30 days. Hope this helps!
注意__gte解释的用法——它的意思是“大于”,可以与数字和时间戳一起使用。这个过滤器将只返回在过去30天内创建的记录。希望这可以帮助!