2011-02-22 54 views
1

我使用「extra」子句創建了模型中三個文本字段中的連接字段 - 我希望能夠做到這一點:q.filter(concatenated__icontains =「y」)但它給了我一個錯誤。還有什麼替代方法?在Django中連接字段值

>>> q = Patient.objects.extra(select={'concatenated': "mrn||' '||first_name||' '||last_name"}) 
>>> q.filter(concatenated__icontains="y") 
Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
    File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 561, in filter 
    return self._filter_or_exclude(False, *args, **kwargs) 
    File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 579, in _filter_or_exclude 
    clone.query.add_q(Q(*args, **kwargs)) 
    File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1170, in add_q 
    can_reuse=used_aliases, force_having=force_having) 
    File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1058, in add_filter 
    negate=negate, process_extras=process_extras) 
    File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1237, in setup_joins 
    "Choices are: %s" % (name, ", ".join(names))) 
FieldError: Cannot resolve keyword 'concatenated' into field. Choices are: first_name, id, last_name, mrn, specimen 

回答

0

我基於普拉薩德的回答最終的解決方案:

from django.db.models import Q 

searchterm='y' 
Patient.objects.filter(Q(mrn__icontains=searchterm) | Q(first_name__icontains=searchterm) | Q(last_name__icontains=searchterm)) 
3

如果你需要的東西超出了這個,

Patient.objects.filter(first_name__icointains='y' | last_name__icontains='y' | mrn__icontains='y') 

你可能不得不求助於原始的SQL。

當然,您可以在上面的過濾器之前或之後添加您的extra

+0

謝謝,這是一個優雅的解決方案,解決了我的問題。 – Toshio 2011-02-22 19:48:49