gpt4 book ai didi

python - Django 1.8 在 lower() 函数上选择 distinct 会抛出 AttributeError

转载 作者:太空狗 更新时间:2023-10-30 01:33:39 25 4
gpt4 key购买 nike

我有一个简单的表格:

class Author(models.Model):
name = models.CharField(max_length=40)

我想使用 Django ORM 编写类似于以下的查询:

SELECT DISTINCT LOWER(name) from my_app_author;

我终于结束了:

Author.objects.annotate(
name_lower=Func(F('name'), function='lower')
).distinct('name_lower')

但我收到错误:

Traceback (most recent call last):
File "/opt/venv/lib/python3.4/site-packages/django/db/models/query.py", line 138, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/opt/venv/lib/python3.4/site-packages/django/db/models/query.py", line 162, in __iter__
self._fetch_all()
File "/opt/venv/lib/python3.4/site-packages/django/db/models/query.py", line 965, in _fetch_all
self._result_cache = list(self.iterator())
File "/opt/venv/lib/python3.4/site-packages/django/db/models/query.py", line 238, in iterator
results = compiler.execute_sql()
File "/opt/venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 829, in execute_sql
sql, params = self.as_sql()
File "/opt/venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 381, in as_sql
distinct_fields = self.get_distinct()
File "/opt/venv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 545, in get_distinct
result.append("%s.%s" % (qn(alias), qn2(target.column)))
AttributeError: 'Func' object has no attribute 'column'

但是当我写的时候:

Author.objects.annotate(
name_lower=Func(F('name'), function='lower')
).distinct('something')

我收到一个错误:

django.core.exceptions.FieldError: 
Cannot resolve keyword 'something' into field.
Choices are: id, name, name_lower, src_id

最佳答案

感谢 @knbk ,

这是 Django 错误 #24986

解决方法是使用:

Author.objects.annotate(
name_lower=Func(F('name'), function='lower')
).values('name_lower').distinct()

关于python - Django 1.8 在 lower() 函数上选择 distinct 会抛出 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30835806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com