开发者

Concatenating field values in Django

开发者 https://www.devze.com 2023-02-12 12:10 出处:网络
I have created with the \"extra\" clause a concatenated field out of three text fields in a model - and I expect to be able to do this: q.filter(concatenated__icontains=\"y\") but it gives me an error

I have created with the "extra" clause a concatenated field out of three text fields in a model - and I expect to be able to do this: q.filter(concatenated__icontains="y") but it gives me an error. What alternatives are there?

>>> 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开发者_StackOverflow中文版_name, id, last_name, mrn, specimen


If you need something beyond this,

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

you might have to resort to raw SQL.

Of course, you can add in your extra either before or after the filter above.


My final solution based on Prasad's answer:

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))
0

精彩评论

暂无评论...
验证码 换一张
取 消