Opened 4 years ago

Closed 4 years ago

#31565 closed New feature (duplicate)

Support GENERATED ALWAYS columns for MySQL and PostgreSQL

Reported by: Louise Grandjonc Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no



in Postgres 12, generated columns have been added:

The value of a generated column is computed from other columns. A generated column can be either stored (in which case it takes up space, and is written/updated like any other column) or virtual.

Here is the example in the postgres docs to create such columns:

    height_cm numeric,
    height_in numeric GENERATED ALWAYS AS (height_cm / 2.54) STORED

I would love to contribute and add this feature. And I'd like to know a bit what other think in terms of design:
Maybe the expression could be a string:

class People(models.Model):
    height_cm = models.FloatField()
    height_in = models.FloatField(always_generated='height_cm / 2.54', stored=True)


Change History (2)

comment:1 by Nick Pope, 4 years ago

Triage Stage: UnreviewedAccepted

This would be nice. I'd imagine tweaking your proposed API to look a bit more like the following:

class Persistence(enum.Enum):

class People(models.Model):
    height_cm = models.FloatField()
    height_in = models.FloatField(generated=F('height_cm') / 2.54, persistence=Persistence.STORED)
  • always_generated seems a bit long and it is always GENERATED ALWAYS AS.
  • It would be nice to build expressions using the ORM with F(), etc.
  • Specifying the "persistence" (is that the best name) keyword with an enum would allow reuse of that elsewhere.

There are a number of complex issues that need to be addressed:

  • The new value needs to be returned on INSERT or UPDATE. (Support for INSERT via RETURNING was added in Django 3.0)
  • Any column with generated needs to be excluded from INSERT or UPDATE queries.
  • We'd need to use a feature flag to specify which "persistence" keywords are supported, i.e. PostgreSQL only supports STORED.

comment:2 by Mariusz Felisiak, 4 years ago

Resolution: duplicate
Status: newclosed

Duplicate of #31300.

Note: See TracTickets for help on using tickets.
Back to Top