tortoise-orm
tortoise-orm copied to clipboard
Function cannot use relations in the scope of annotate
Describe the bug Function cannot use relations in the scope of annotate. got error
tortoise.exceptions.FieldError: There is no non-virtual field points__value1 on Model User
To Reproduce
from tortoise import Tortoise, fields, run_async
from tortoise.expressions import F
from tortoise.functions import Coalesce, Sum
from tortoise.models import Model
class User(Model):
id = fields.IntField(pk=True)
name = fields.TextField()
points: fields.ReverseRelation["Point"]
class Point(Model):
id = fields.IntField(pk=True)
value1 = fields.TextField()
value2 = fields.TextField()
user = fields.ForeignKeyField("models.User", related_name="points")
async def run():
await Tortoise.init(db_url="sqlite://:memory:", modules={"models": ["__main__"]})
await Tortoise.generate_schemas()
user = await User.create(name="user1")
await Point.create(user_id=user.id, value1=2, value2=5)
await Point.create(user_id=user.id, value1=3, value2=10)
res = (
await User.all()
.limit(2)
.offset(0)
.annotate(value_total=Coalesce(
Sum(
F('points__value1') * F('points__value2')
),
0
))
.values('id', 'name', 'value_total')
)
print(res)
if __name__ == "__main__":
run_async(run())
Expected behavior
SELECT `user`.`id`, `user`.`name`, COALESCE(SUM(`user`.`value1` * `user`.`value2`), 0) `value_total`
FROM `users`
Additional context Tortoise 0.17.8
Temporary solution
Sum(
- F('points__value1') * F('points__value2')
+ RawSQL('points.value1 * points.value2')
),
If the F expression is changed to RawSQL can work, But the _filter of Sum is invalid...
I am interested on working on this issue, is there somewhere I can get in touch with the maintainers to work on this issue?