Django-无法通过外键first_name

时间:2018-07-20 20:52:42

标签: mysql django django-models django-views

因此,目前,您可以通过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 个答案:

答案 0 :(得分:1)

在这里,您仅构造一个 string ,也许它的形状类似于Python代码,但这不是将任意参数 names 传递给函数的方式。

您可以在这里使用关键字参数,并构建一个字典,该字典将 key (参数名称)映射为 value (应与该参数对应的值),例如:

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')

如果要过滤多个项目,则可以构造具有多个键的字典。但是请注意,键(如参数名称)不能发生冲突(调用具有两次或多次相同的 named 参数的函数)。

此外,请注意,User模型包含(散列)密码和其他敏感数据,您可能希望避免对某些字段进行过滤,因为可以使用此机制来破解数据退出系统。