小编典典

Django ORM:按额外属性过滤

python

我想通过串联字符串过滤某些数据库对象。

正常的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, (...)

这是错误还是功能?我怎样才能解决这个问题?

谢谢。


阅读 221

收藏
2020-12-20

共1个答案

小编典典

这不是错误。filter()仅检查模型定义,因此不会将其识别fullName为已声明的字段(因为它不是-这是查询中的额外参数)。

您可以使用添加fullName到:WHERE``extra()

Person.objects.extra(where=["fullName LIKE %s"], params=["Alexei%"])
2020-12-20