Visitar URL original
Add support for generated columns · Issue #196 · ormar-orm/ormar · GitHub
Skip to content

Add support for generated columns #196

Open

Description

@m1racoli

Is your feature request related to a problem? Please describe.

I would like to efficiently query my model on a field which is calculated from another field.

I expect the following behaviour of this field:

  • indices: i should be able to create an index on the calculated field
  • db side filtering and aggregations: I should be able to filter and group by that field like any other DB column
  • read-only: I should not be able to update the field
  • follow updates from parent field: when the parent has changed, the calculated field changes too

Describe the solution you'd like

I would like to be able to define a field as generated.

import datetime
import ormar
from .base import BaseMeta


class Foo(ormar.Model):
    class Meta(BaseMeta):
        pass

    id: int = ormar.Integer(primary_key=True)
    dt: datetime.date = ormar.Date()
    year: int = ormar.Integer(generated_as="CAST(strftime('%Y', dt) AS INTEGER)", stored=False, index=True)

Describe alternatives you've considered

Some of this behaviour can be achieved by defining signals for pre-update and pre-save, which would ensure the calculated column is always stored correctly.

Anyways, this does not prevent me of changing the field value the model or in the DB.

I've also considered ormar.property_field, but this would require all filtering and grouping being implemented on application side.

Additional context

Activity

  1. collerek commented on May 21, 2021

    @collerek
    Collaborator

    Yeah, seems like a good idea, seems also like sqlalchemy supports them so it should be possible sqlalchemy/sqlalchemy#4894

  2. sorasful commented on Jan 3, 2022

    @sorasful

    Hmm, just to be sure, for now there's no possibility to filter data when using ormar.property_field right ?

    I tried using Django syntax but got a KeyError. Maybe there's a workaround ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions