【问题标题】:Related Field got invalid lookup: icontains相关字段查找无效:​​icontains
【发布时间】:2016-01-26 11:36:31
【问题描述】:

我正在尝试在我的主页中包含一个搜索字段。它适用于某些模块领域。我的问题是当我使用 ForeignKey 字段时(如果我错了,请纠正我)。

models.py

class Location(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    my_location = models.CharField(max_length=120, choices=LOCATION_CHOICES)
    update_date = models.DateField(auto_now=True, null=True)

    def __str__(self):
        return self.my_location


class UserProfile(models.Model):

    user = models.ForeignKey(User)
    # The additional attributes we wish to include.
    user_base = models.CharField(max_length=120, choices=LOCATION_CHOICES)
    user_position = models.CharField(max_length=120)
    user_phone = models.PositiveIntegerField()

    def __unicode__(self):
        return self.user.username

views.py

def search_by_location(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        locations = Location.objects.filter(my_location__icontains=q).order_by('-update_date')
    else:
        locations = Location.objects.order_by('-update_date')
context = {'locations': locations}
return render(request, 'index.html', context)

我的问题是如果我在过滤器查询中使用 user 而不是 my_location 我会收到错误:

相关字段的查找无效:​​icontains

请提供有关如何排除故障的任何建议或我可以阅读的任何文档。

【问题讨论】:

    标签: python django


    【解决方案1】:

    您可以在文本字段上使用icontains 查找。 user 是相关(整数)字段。而不是user 使用user__username

    locations = Location.objects.filter(user__username__icontains=q)
    

    【讨论】:

      【解决方案2】:
      class SearchView(ListView):
      model = Profile
      template_name = 'blog/search_results.html'
      context_object_name = 'all_search_results'
      def get_context_data(self, **kwargs):
          context = super().get_context_data(**kwargs)
          user_name = self.request.GET.get('search', '')
          context['all_search_results'] = Profile.objects.filter(user__username__icontains=user_name )
          return context  
      

      这是另一个关于如何过滤对象的示例。如果搜索用户,请记住用户user_username__icontains=user_name

      还请记住,如果您使用Profile,您将获得与使用User 不同的id

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多