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?

Asked By: Ian Fiddes

||

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))
Answered By: el.atomo

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))
Answered By: Little Elite
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.