创建复杂查询?你知道吗
请帮忙解决这个问题。你知道吗
我写了一个过滤器来搜索人。筛选器包含2个字段:“姓名”、“出生日期”
朋友_搜索.html地址:
<form class="left filter" action="{% url 'friends_search' %}" method="POST">
{% csrf_token %}
<div class="cell">
<label class="label lbl_name" for="fld_name">Имя</label>
<input class="fld_name" type="text" name="fld_name" id="fld_name" value="{% if post.fld_name %}{{ post.fld_name }}{% endif %}" />
</div>
<div class="cell">
<label class="label lbl_birth_date" for="fld_birth_date">Дата рождения</label>
<input class="fld_birth_date datepicker" type="text" name="fld_birth_date" id="fld_birth_date" value="{% if post.fld_birth_date %}{{ post.fld_birth_date }}{% endif %}" />
</div>
<div class="cell">
<input class="submit btn btn-default btn-block" type="submit" name="fld_submit" id="fld_submit" value="Найти" />
</div>
</form>
你知道吗视图.py地址:
@login_required
def friends_search(request):
search_result = None
post = None
if request.method == 'POST':
post = request.POST
if request.POST.get('fld_name'):
try:
fld_name = request.POST.get('fld_name')
fld_birth_date = request.POST.get('fld_birth_date')
if q_name:
q_name = Q(nickname__icontains=fld_name.strip()))
if q_birth_date:
q_birth_date = Q(birth_date__icontains=fld_birth_date.strip())
search_result = UserProfile.objects.filter(q_name).filter(q_birth_date) #???????????????????????????
if not search_result:
search_result = 'null'
except Exception as exc:
search_result = 'error'
t = loader.get_template('friends_search.html')
c = RequestContext(request, {
'city_list': UserProfile.get_city_list(),
'post': post,
}])
return HttpResponse(t.render(c))
你知道吗型号.py地址:
class UserProfile(User):
nickname = models.CharField(
'Отображаемое имя',
max_length=30,
blank=False,
)
birth_date = models.DateField(
'Дата рождения',
blank=True,
null=True,
)
问题是我不能从两个领域看:
search_result = UserProfile.objects.filter (q_name). filter (q_birth_date)
但我可以搜索特定字段:
search_result = UserProfile.objects.filter (q_name)
&
search_result = UserProfile.objects.filter (q_birth_date)
我需要你同时用两个字段搜索
将搜索这两个,即昵称是和出生日期是。你知道吗
如果要搜索其中一个或两个字段,可以将视图更新为
您可以去掉
search_result
变量,因为qs
与此相同。你知道吗永远不要捕获基类
Exception
,除非您正确地处理它(即记录错误消息等)。为什么?因为except
子句隐藏了代码中真正的问题,使调试成为一个巨大的麻烦request.POST
对象只包含普通字符串。虽然fld_birth_date
可能是日期格式的字符串,但不能用字符串对象过滤DateField
。您需要一个实际的date
对象来过滤。你知道吗您需要做的是将字符串转换为日期对象。例如,如果您的日期总是遵循
dd-mm-YYYY
格式,您可以:除此之外,还可以使用
if q_name
和if q_birth_date
,但两者都没有定义,都会引发另一个异常。你知道吗代码的
if request.method == 'POST'
部分可能如下所示:或者如果您希望在姓名或出生日期匹配时得到结果:
相关问题 更多 >
编程相关推荐