【发布时间】: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
请提供有关如何排除故障的任何建议或我可以阅读的任何文档。
【问题讨论】: