Django distinct不起作用 [英] Django distinct is not working
问题描述
我有一个从查询过滤掉重复的问题。
我使用Django 1.4与Postgres 8.4.13
I have a problem filtering out duplicates from a query. I'm using Django 1.4 with Postgres 8.4.13
我在我的模型对象上使用这个查询(它是一个jquery自动完成)
I use this query on my model object (it is a jquery autocomplete)
term = request.GET.get('term')
field = request.GET.get('field')
filter = field + '__' + 'icontains'
model_results = teilnehmer.objects.filter(**{filter: term}).order_by().distinct()
results = [ getattr(x, field) for x in model_results ]
output = simplejson.dumps(results)
它工作不错,给我任何搜索字词在模型的任何领域的结果。
但它显示每一个单击。所以如果名字史密斯在表10次,它给我一个10次史密斯的阵列。
它应该作为一个建议工具。我读了有关distinct的内容,并尝试使用它(如上所述),但它不起作用。
It works nice, giving me results for any search term in any field of the model. But it shows every single hit. So if the name "Smith" is in the table 10 times, it gives me an array of 10 times "Smith". It should work as a suggestion-tool. I read about distinct and tried to use it (as above) but it doesn't work.
任何想法?
提前感谢
Conrad
推荐答案
命名为 distinct
function:
Pass field name to distinct
function:
model_results = teilnehmer.objects.filter(**{filter: term}).order_by().distinct(field)
非常不安全,因为您应该将 GET
值验证,然后再将它们传递给 QuerySet
。也可以使用django表单?
Also your approach is very insecure because you should validate GET
values before passing them to QuerySet
. Use django forms maybe?
另请阅读有关 distinct的文档
function here
Also read the docs about distinct
function here
这篇关于Django distinct不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!