tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.37k stars 355 forks source link

computed column #587

Open agent666 opened 3 years ago

agent666 commented 3 years ago

Is it possible to add a computed column to a sqlite database with Tortoise ORM? And if it is how do i do it?

vitalykireev commented 3 years ago

Сan I join this question. Is it possible to make a calculated field that uses stored procedures in DB?

For example, is it possible in Model adding next field:

class Mission(Model):
    targets = ReverseRelation["Target"]
    targets_count = CalculatedField(int, "get_targets_count", "id")

class Target(Model):
    mission: ForeignKeyRelation[Mission] = ForeignKeyField("models.Mission", related_name="targets")

where CalculatedField means that will be used stored procedure with parameter

CREATE OR REPLACE FUNCTION public.get_targets_count(m_id integer)
 RETURNS bigint
 LANGUAGE sql
AS $function$
select count(*) from target where mission_id = m_id;
$function$;

This is very useful for queries with relationships for submodels. Using annotate doesn't seem to solve the problem with related fields.

mazulo commented 4 months ago

This would be extremely helpful. Django already released on version 5.0 the GeneratedField, which basically creates a field that is always computed based on other fields in the model.

intigratech commented 1 month ago

I think this would be a great addition as well.