我正在尝试从我的数据库中获取满足指定条件的所有对象。从我的模型Training
我需要获取与登录用户连接的所有对象,日期在指定范围内,并指定训练类型。
型号:
class Training(models.Model):
user = models.ForeignKey(User)
date = models.DateField()
length = models.TimeField()
distance = models.FloatField()
type = models.CharField(max_length=2,choices=TRAINING_TYPE)
caloriesBurnt = models.FloatField()
weight = models.FloatField()
description = models.TextField(max_length=25)
使用过滤器查看:
def ReportRequest(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
if request.method == 'POST':
form = ReportForm(request.POST)
if form.is_valid():
usrname = request.user
q = Training.objects.filter(user=usrname)
q = Training.objects.filter(date__range=[form.cleaned_data['start'], form.cleaned_data['end']])
q = Training.objects.filter(type=form.cleaned_data['type'])
quantity = q.count
if quantity == 0:
return HttpResponseRedirect('/notrainings/')
avg_length = q.aggregate(Avg('length'))
avg_distance = q.aggregate(Avg('distance'))
avg_calories = q.aggregate(Avg('caloriesBurnt'))
return HttpResponseRedirect('/report/')
else:
return render_to_response('reportform.html', {'form':form}, context_instance=RequestContext(request))
else:
form = ReportForm()
return render_to_response('reportform.html',{'form':form}, context_instance = RequestContext(request))
用户设置数据范围和培训类型的形式:
class ReportForm(forms.Form):
start = forms.DateField(widget=SelectDateWidget(), initial=date.today())
end = forms.DateField(widget=SelectDateWidget(),initial=date.today())
type = forms.ChoiceField(required=True, choices=ACTIVITY_CHOICES, initial=RUNNING)
我的问题:在我的数据库中,所有培训都是在12月9日和10日进行的。当我从12月2日到12日在我的表单中设置日期范围时,它应该将我重定向到/notrainings/
。但事实并非如此。无论我使用quantity = q.count
还是quantity = q.count()
。
我非常感谢这个主题的帮助。
解决了,感谢Mihai& ruddra
答案 0 :(得分:2)
您可以这样做:
q = Training.objects.filter(user=usrname).filter(date__range=[form.cleaned_data['start'], form.cleaned_data['end']]).filter(type=form.cleaned_data['type'])
count = q.count()
答案 1 :(得分:1)
你的问题很简单。您始终在查询Training
,而不是存储您的部分结果。存储的最后一个查询是这一个:
q = Training.objects.filter(type=form.cleaned_data['type'])
所以实际上你只是过滤type
你应该做的是:
q = Training.objects.filter(user=usrname)
q = q.filter(date__range=[form.cleaned_data['start'], form.cleaned_data['end']])
q = q.filter(type=form.cleaned_data['type'])
或者如果您想要一次性完成所有内容:
q = Training.objects.filter(
user=usrname,
date__range=[form.cleaned_data['start'], form.cleaned_data['end']],
type=form.cleaned_data['type'],
)