我想通過連接字符串過濾一些數據庫對象。Django ORM:按額外屬性過濾
正常的SQL查詢是:
SELECT concat(firstName, ' ', name) FROM person WHERE CONCAT(firstName, ' ', name) LIKE "a%";
在這個模型中,我創建了一個經理叫PersonObjects:
class PersonObjects(Manager):
attrs = {
'fullName': "CONCAT(firstName, ' ', name)"
}
def get_query_set(self):
return super(PersonObjects, self).get_query_set().extra(
select=self.attrs)
我也是在我的模型配置此:
objects = managers.PersonObjects()
現在訪問fullName適用於單個對象:
>>> p = models.Person.objects.get(pk=4)
>>> p.fullName
u'Fred Borminski'
但它不能在過濾器工作:
>>> p = models.Person.objects.filter(fullName__startswith='Alexei')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/django/db/models/manager.py", line 141, in filter
return self.get_query_set().filter(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 550, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 568, 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 1128, in add_q
can_reuse=used_aliases)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1026, in add_filter
negate=negate, process_extras=process_extras)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1191, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'fullName' into field. Choices are: firstName, gender, name, (...)
這是一個錯誤或功能?我怎樣才能解決這個問題?
謝謝。
不幸的是,這不起作用。它仍抱怨沒有找到fullName屬性。儘管直接檢索對象的fullName屬性。這種「額外」方法是否以某種方式覆蓋了管理器之前設置的額外屬性? – 2010-12-09 09:24:52