相关字段无效查找:icontains

mar*_*man 16 python django

我想在我的主页中包含一个搜索字段.它适用于某些模块字段.我的问题是当我使用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
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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

相关字段无效查找:icontains

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

Tom*_*Rup 37

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

locations = Location.objects.filter(user__username__icontains=q)
Run Code Online (Sandbox Code Playgroud)