peewee multiplying integer fields by floats for linear expression – replaces numbers between 0 and 1 with 0
Question:
I am trying to add a linear inequality to a select statement in peewee,
r = r.where((tgt.attrs.NumberMissingOriginalIntrons <= 0.5 * tgt.attrs.NumberIntrons - 0.5))
Where r
is an existing query being added to and tgt.attrs
is a table.
However, when this is converted to SQL, it looks like this:
WHERE ("t1"."NumberMissingOriginalIntrons" <= ((? * "t1"."NumberIntrons") - ?)) [0, 0]
But the expression I actually want is:
WHERE ("t1"."NumberMissingOriginalIntrons" <= ((? * "t1"."NumberIntrons") - ?)) [0.5, 0.5]
Based on some testing, I have realized that this only fails if the values are between 0 and 1. Why is this? Does this have to do with the column definitions being Integer
?
Answers:
Yes, it’s related with your column field type (Integer
).
Nevertheless, you can use the cast function:
from playhouse.shortcuts import cast
...
my_field = tgt.attrs.NumberMissingOriginalIntrons
r = r.where((cast(my_field, 'float') <= 0.5 * cast(my_field, 'float') - 0.5))
In recent versions(Currently, up to v3.15), this function is inside peewee itself and there is no need to import playhous.shortcuts .
Also, the function name been changed from cast to Cast a few years after el.atomo answered the question. (as mentioned in the Cast documentation)
So for the code example above, we will have:
my_field = tgt.attrs.NumberMissingOriginalIntrons
r = r.where((cast(my_field, 'float') <= 0.5 * Cast(my_field, 'float') - 0.5))
I am trying to add a linear inequality to a select statement in peewee,
r = r.where((tgt.attrs.NumberMissingOriginalIntrons <= 0.5 * tgt.attrs.NumberIntrons - 0.5))
Where r
is an existing query being added to and tgt.attrs
is a table.
However, when this is converted to SQL, it looks like this:
WHERE ("t1"."NumberMissingOriginalIntrons" <= ((? * "t1"."NumberIntrons") - ?)) [0, 0]
But the expression I actually want is:
WHERE ("t1"."NumberMissingOriginalIntrons" <= ((? * "t1"."NumberIntrons") - ?)) [0.5, 0.5]
Based on some testing, I have realized that this only fails if the values are between 0 and 1. Why is this? Does this have to do with the column definitions being Integer
?
Yes, it’s related with your column field type (Integer
).
Nevertheless, you can use the cast function:
from playhouse.shortcuts import cast
...
my_field = tgt.attrs.NumberMissingOriginalIntrons
r = r.where((cast(my_field, 'float') <= 0.5 * cast(my_field, 'float') - 0.5))
In recent versions(Currently, up to v3.15), this function is inside peewee itself and there is no need to import playhous.shortcuts .
Also, the function name been changed from cast to Cast a few years after el.atomo answered the question. (as mentioned in the Cast documentation)
So for the code example above, we will have:
my_field = tgt.attrs.NumberMissingOriginalIntrons
r = r.where((cast(my_field, 'float') <= 0.5 * Cast(my_field, 'float') - 0.5))