我想根据三个用户输入过滤查询。离开城市,到达城市和日期。出发城市和到达城市位于同一个名为Route的桌子上,而TravelDate是Route中的外键。 我的模特
class TravelDate(models.Model):
start_date = models.DateField(null = True)
interval = models.IntegerField(null = True)
class Route(models.Model):
depart_city = models.CharField(max_length=50, null=True, blank=False)
arrive_city = models.CharField(max_length=50, null=True, blank=False)
driver = models.ForeignKey(Driver)
schedule = models.ForeignKey(Schedule)
traveldate = models.ForeignKey(TravelDate)
我的观点
def newpage(request):
if 'origin' in request.GET and request.GET['origin']:
q = request.GET['origin']
c = request.GET['dest']
d = request.GET['travelDate']
results = Route.objects.filter(depart_city=q, arrive_city=c)
return render(request,'busapp/newpage.html', {'results': results})
else:
return render(request, 'busapp/newpage.html',{})
在视图中,如何根据用户输入过滤一个查询来过滤那些路线的depart_city,arrival_city和TravelDate。如果在该日期从城市A到城市B的公共汽车将通过执行类似if (d - TravelDate.start_date)% TravelDate.interval =0
的操作来计算,然后将结果显示给用户。
我无法做到这一点。我是Django的新手并且正在努力学习。
答案 0 :(得分:1)
将间隔保持为IntegerField
views.py
from datetime import datetime, timedelta
q = request.GET['origin']
c = request.GET['dest']
d = request.GET['travelDate']
# d format is '20171122',convert str to date
start_date = datetime.strptime(d, "%Y%m%d").date()
results = Route.objects.filter(depart_city=q, arrive_city=c)
routes = []
for route in results:
if (start_date > date) and ((start_date - route.traveldate.start_date) % timedelta(days=route.traveldate.interva)) == timedelta(days=0):
routes.append(route)
return render(request,'busapp/newpage.html', {'results': routes})