Django搜索字段无法正常工作

时间:2015-03-19 21:15:19

标签: python django search django-models django-views

我希望能够搜索用户,并将其指向所有用户的列表。

当我尝试搜索功能时,收到此错误:相关字段无效查找:icontains。

它追溯到这一行:

clients = LessonCount.objects.filter(user__icontains=q)

有什么想法吗?提前谢谢!

views.py:

def search(request):
try:
    q = request.GET.get('q')
except:
    q = None

if q:
    clients = LessonCount.objects.filter(user__icontains=q)
    context = {
        'query': q, 
        'clients': clients
    }
    template = 'clients.html'
else:
    context = {}
    template = 'contact.html'
return render(request, template, context)

models.py:

class LessonCount(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
lesson_current_amount = models.PositiveIntegerField(default=0, verbose_name='Current Number of Lessons')

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

class Meta:
    ordering = ['-user']

def update_lesson_count(self):
    if self.lesson_current_amount > 0:
        self.user.is_member = True
        self.user.save()
    elif self.lesson_current_amount <= 0:
        self.user.is_member = False
        self.user.save()
    else:
        pass

1 个答案:

答案 0 :(得分:2)

(user__icontains=q)正在调用用户对象上的icontains查找。我认为你应该做的是(user__username__icontains=q),它会对用户的名字进行查询。