[英]Why peewee coerces select column to integer
I can't use sqlite function group_concat() in peewee. 我不能在peewee中使用sqlite函数group_concat()。 Here is complete snipet.
这是完整的片段。 Somehow peewee want to convert result of group_concat() to integer, while it is string ("1,2").
peewee希望以某种方式将group_concat()的结果转换为整数(字符串(“ 1,2”))。 I can't find the way to suppress it.
我找不到抑制它的方法。
from peewee import *
db = SqliteDatabase(':memory:')
class Test(Model):
name = CharField()
score = IntegerField()
class Meta:
database = db
db.create_tables([Test])
Test.create(name='A', score=1).save()
Test.create(name='A', score=2).save()
#select name, group_concat(score) from Test group by name
for t in Test.select(Test.name, fn.group_concat(Test.score)).order_by(Test.name):
pass
It produces following error: 它产生以下错误:
Traceback (most recent call last):
File "C:\Users\u_tem0m\Dropbox\Wrk\sgo\broken.py", line 17, in <module>
for t in Test.select(Test.name, fn.group_concat(Test.score)).order_by(Test.name):
File "C:\Program Files\Python 3.5\lib\site-packages\peewee.py", line 1938, in next
obj = self.qrw.iterate()
File "C:\Program Files\Python 3.5\lib\site-packages\peewee.py", line 1995, in iterate
return self.process_row(row)
File "C:\Program Files\Python 3.5\lib\site-packages\peewee.py", line 2070, in process_row
setattr(instance, column, func(row[i]))
File "C:\Program Files\Python 3.5\lib\site-packages\peewee.py", line 874, in python_value
return value if value is None else self.coerce(value)
ValueError: invalid literal for int() with base 10: '1,2'
Try adding a coerce(False)
to your call to group_concat: 尝试在对group_concat的调用中添加一个
coerce(False)
:
query = (Test
.select(Test.name, fn.GROUP_CONCAT(Test.score).coerce(False))
.order_by(Test.name))
for t in query:
pass
Peewee sees that Test.score is an integer field, so whenever a function is called on that column, Peewee will try to convert the result back to an int. Peewee看到Test.score是一个整数字段,因此无论何时在该列上调用函数,Peewee都会尝试将结果转换回int。 The problem is that group_concat returns a string, so we must tell Peewee not to mess with the return value.
问题是group_concat返回一个字符串,因此我们必须告诉Peewee不要弄乱返回值。
Just found what result of fn.group_concat(""+Test.score) don't cast to integer. 刚刚发现fn.group_concat(“” + Test.score)的结果没有转换为整数。 But I think resulting sql maybe less optimal
但是我认为生成的sql可能不太理想
SELECT "t1"."name", group_concat(? + "t1"."score") AS allscore FROM "test" AS t1 ORDER BY "t1"."name" ['']
选择“ t1”。“ name”,group_concat(?+“ t1”。“ score”)AS allscore FROM“ test” AS t1 OR BY BY“ t1”。“ name” [“]
Do anybody knows more elegant way? 有人知道更优雅的方式吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.