django-无法按外键名筛选

guykilcj  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(382)

所以,目前我这样做,你可以搜索用户,参加了一个偶数,通过一些过滤器是 first_name, last_name, username 当前错误为
要解包的值太多(应为2)
视图中的错误行:

  1. makefilter = "user__"+searchfilter+"__contains="+searchinput
  2. usersearch = TeamMembership.objects.filter(makefilter)

如何通过过滤器成功搜索?

我的观点.py:

  1. def volunteer(request):
  2. ## init context
  3. context = {}
  4. ## Get filters if somes
  5. searchfilter = request.GET.get('filter', None)
  6. searchinput = request.GET.get('searchinput', None)
  7. ## Checks if filter is not none or null or empty
  8. if searchfilter != "" and searchfilter != None and searchinput != "" and searchinput != None:
  9. ## Great now check what filter is used
  10. ## Now strip the filters for whitespaces
  11. searchfilter.strip()
  12. searchinput.strip()
  13. ## This filter is for teams
  14. if searchfilter == "teamname":
  15. teamsearch = Team.objects.all().filter(name__contains=searchinput)
  16. context['teams'] = True
  17. context['search'] = teamsearch
  18. ## This filter is for users
  19. elif searchfilter == "first_name" or searchfilter == "last_name" or searchfilter == "username" or searchfilter == "phone":
  20. makefilter = "user__"+searchfilter+"__contains="+searchinput
  21. usersearch = TeamMembership.objects.filter(makefilter)
  22. context['users'] = True
  23. context['search'] = usersearch
  24. return render(request, 'volunteer/hqvolunteer.html', context)

我的模型我试图搜索的用户模型是标准django auth:

  1. class TeamMembership(models.Model):
  2. user = models.ForeignKey(User)
  3. team = models.ForeignKey(Team)
  4. ingroup = models.BooleanField(default=False)
  5. leader = models.BooleanField(default=False)
  6. groupleader = models.BooleanField(default=False)
kse8i1jr

kse8i1jr1#

在这里,您只需要构造一个字符串,也许它的形状类似于python代码,但这并不是您将任意参数名传递给函数的方式。
这里可以使用关键字参数,并构造一个字典,将键(参数的名称)Map到值(应该与该参数对应的值),如:

  1. some_dict = { "user__"+searchfilter+"__contains": searchinput}
  2. usersearch = TeamMembership.objects.filter(**some_dict)

万一 search_filter 例如 'email' ,和 searchinput 存在 'bar' ,则会导致 some_dict 存在 { 'user__email__contains': 'bar' } ,并呼叫:

  1. TeamMembership.objects.filter(**{ 'user__email__contains': 'bar' })

相当于:

  1. TeamMembership.objects.filter(user__email__contains='bar')

如果要筛选多个项,可以构造具有多个键的字典。但是请注意,键(如参数名)不能冲突(使用两次或两次以上相同的命名参数调用函数)。
此外,请注意 User 模型包含(散列)密码和其他敏感数据,您可能希望避免对某些字段进行过滤,因为可以使用此机制从系统中破解数据。

展开查看全部

相关问题