提问人:Melonendk 提问时间:7/21/2018 更新时间:7/21/2018 访问量:129
Django - 无法按外键first_name过滤
Django - Cannot filter by foreign key first_name
问:
所以目前我正在这样做,你可以通过一些过滤器来搜索正在参加偶数的用户first_name, last_name, username
当前错误
要解压缩的值太多(预期为 2)
视图中的误差线:
makefilter = "user__"+searchfilter+"__contains="+searchinput
usersearch = TeamMembership.objects.filter(makefilter)
如何通过过滤器成功搜索?
我 views.py:
def volunteer(request):
## init context
context = {}
## Get filters if somes
searchfilter = request.GET.get('filter', None)
searchinput = request.GET.get('searchinput', None)
## Checks if filter is not none or null or empty
if searchfilter != "" and searchfilter != None and searchinput != "" and searchinput != None:
## Great now check what filter is used
## Now strip the filters for whitespaces
searchfilter.strip()
searchinput.strip()
## This filter is for teams
if searchfilter == "teamname":
teamsearch = Team.objects.all().filter(name__contains=searchinput)
context['teams'] = True
context['search'] = teamsearch
## This filter is for users
elif searchfilter == "first_name" or searchfilter == "last_name" or searchfilter == "username" or searchfilter == "phone":
makefilter = "user__"+searchfilter+"__contains="+searchinput
usersearch = TeamMembership.objects.filter(makefilter)
context['users'] = True
context['search'] = usersearch
return render(request, 'volunteer/hqvolunteer.html', context)
我的模型我试图搜索用户模型是标准的 Django 身份验证:
class TeamMembership(models.Model):
user = models.ForeignKey(User)
team = models.ForeignKey(Team)
ingroup = models.BooleanField(default=False)
leader = models.BooleanField(default=False)
groupleader = models.BooleanField(default=False)
答:
1赞
willeM_ Van Onsem
7/21/2018
#1
在这里,你只构造一个字符串,也许,它的形状类似于 Python 代码,但这不是你向函数传递任意参数名称的方式。
您可以在此处使用关键字参数,并构造一个字典,将键(参数的名称)映射到值(应与该参数对应的值),例如:
some_dict = { "user__"+searchfilter+"__contains": searchinput}
usersearch = TeamMembership.objects.filter(**some_dict)
例如,如果 是 和 是 ,那么这将导致 是 和 调用:search_filter
'email'
searchinput
'bar'
some_dict
{ 'user__email__contains': 'bar' }
TeamMembership.objects.filter(**{ 'user__email__contains': 'bar' })
相当于:
TeamMembership.objects.filter(user__email__contains='bar')
如果要筛选多个项目,可以构造具有多个键的字典。但请注意,键(如参数名称)不能冲突(调用具有两次或更多相同命名参数的函数)。
此外,请注意,模型包含(散列)密码和其他敏感数据,您可能希望避免对某些字段进行过滤,因为可以使用此机制将数据从系统中剔除。User
评论
1赞
Melonendk
7/21/2018
非常感谢你,我以前从未用外键过滤过,所以这对我来说是新的,当然不是所有的字段都可以使用
评论
iteritems
items