Python 相关字段查找无效:icontains
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35012942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Related Field got invalid lookup: icontains
提问by marwan h-sleiman
I am trying to include a search field inside my home page. It works for some of the module field. My problem is when I use a ForeignKey field (correct me please if I am wrong).
我正在尝试在我的主页中包含一个搜索字段。它适用于一些模块领域。我的问题是当我使用 ForeignKey 字段时(如果我错了,请纠正我)。
models.py
模型.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
视图.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)
My problem is if I use user
inside the filter query instead of my_location
I receive the error:
我的问题是,如果我user
在过滤器查询中使用而不是my_location
收到错误:
Related Field got invalid lookup: icontains
相关字段查找无效:icontains
Please any advice on how to troubleshoot or any documentation I can read.
请提供有关如何排除故障的任何建议或我可以阅读的任何文档。
采纳答案by Tomasz Jakub Rup
You can use icontains
lookup on text fields. user
is related (integer) field. Instead of user
use user__username
.
您可以icontains
在文本字段上使用查找。user
是相关(整数)字段。而不是user
使用user__username
.
locations = Location.objects.filter(user__username__icontains=q)