tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

computed column

Open agent666 opened this issue 5 years ago • 3 comments

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

agent666 avatar Dec 16 '20 00:12 agent666

С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.

vitalykireev avatar Dec 18 '20 23:12 vitalykireev

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.

mazulo avatar Feb 22 '24 20:02 mazulo

I think this would be a great addition as well.

intigratech avatar May 20 '24 15:05 intigratech