You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I used the GitHub search to find a similar issue and didn't find it.
I searched the SQLModel documentation, with the integrated search.
I already searched in Google "How to X in SQLModel" and didn't find any information.
I already read and followed all the tutorial in the docs and didn't find an answer.
I already checked if it is not related to SQLModel but to Pydantic.
I already checked if it is not related to SQLModel but to SQLAlchemy.
Commit to Help
I commit to help with one of those options 👆
Example Code
classAlbum(SQLModel):
title: strslug: strdescription: str# what i've tried but doesn't work e.g : # slug: str = column_property(slugify(title))# E NameError: name 'title' is not definedclassAlbum(SQLModel):
title: strslug: str=column_property(slugify(title))
description: str
Description
I'm trying to generate a column named "slug" that is a slugified version of "title" so it should be persisted in database, and be updated when title changes.
But so far no luck, I've looked at column property but didn't manage to make it work with SQLModel. I saw that there are events "before update" ... but I don't think this is the way to go
@FabiEbert Hello, yeah that's what I ended up doing. But I don't feel like is the cleaner way you know. Also, if you want the slug to be updated each time you update the title you need to add this in your model
This results in in "column Parent.child_count does not exist."
Reacted by Fredrik Karlsson, Nicolas Chaulet, Piotr Karpiński, ljnsn, Maxime Laplace, angel007sya, joshrosenblum, Thijs Damsma, Andrew Parsons, Stefan Uddenberg and 6 more
I think this is one of biggest SQLModel drawbacks I've encountered.
I tried the root-validator approach (which needs validate_assignment=True in order to get the computer column properly updated), but the root validator method is sometime invoked with an incomplete dict (having the additional _sa_instance_state field, but without other required fields such as required_field1 in the example below).
I am trying to use the root validator in a 'mix-in' class, in order to calculate an hash-value on a subset of the model fields.
>>>Album(title='A Title With Many Spaces', description='I am the description')
Album(title='A Title With Many Spaces', description='I am the description', slug='a-title-with-many-spaces')
Note that this solution computes the 'column' each time it is accessed and does not create a new column in the database. However, when disregarding efficiency considerations, I believe that this is a good workaround for many cases.
Application to other cases
You can replace the code in slug() with whatever your need is. You can even access relationship attributes:
classArticle(SQLModel, table=True):
__tablename__="food_article"id: int|None=Field(default=None, primary_key=True)
price_history: list["PriceHistory"] =Relationship()
@computed_field@propertydefunit_price_gross(self) ->float|None:
"""Returns the most recent price from self.price_history."""ifself.price_history:
prices_sorted=sorted(
self.price_history,
key=lambdaitem: item.valid_from,
reverse=True
)
current_price=prices_sorted[0].unit_price_grossreturncurrent_priceelse:
returnNone
@ErikFub in your example slug is available as a property on class but is not actually made as a column in the database table. Is that what you are seeing as well?
I believe OPs original question wanted the slug field/value to be persisted to the database.
I'm using the latest sqlmodel version 0.14 and pydantic 2.0.
class Document:
id: ...
text: ...
author: #expensively calculated by parsing the text through an LLM, ideally only ever happens once
key_points: # same as above
it would be amazing if we could simply do some form of @computed annotation on those fields together with a function that gets as input the object and can then calculate the value which then gets returned and persisted so the next time it doesn't get re-calculated
I think this issue should be closed. Author wanted to create real column in DB that would be automatically calculated (updated) on row update. column_property doesn't do that. It doesn't create real column, but just calculates the value during the query time on DB side.
So, if it's strict that real column should be created, than let's start from trying to come up with the code example with pure SQLAlchemy.
If that requirement is not strict, let's start from defining requirements.
Anyway, I would suggest closing this and opening a discussion if needed.
If we understand that there is no appropriate way to achieve what is needed, we can create a feature request with clear description.
Activity
sorasful commentedon Oct 30, 2021
I tried using
@hybrid_propertydecorator from sqlalchemy, but it raises :And if I set :
We now have :
FabiEbert commentedon Nov 1, 2021
Hi @sorasful,
So basically you want the
slug = slugify(title)?To do so I would do the following:
The input:
{ "title": "My Album Title", "description": "This is a description" }The output I got:
{ "title": "My Album Title", "description": "This is a description", "slug": "my-album-title" }sorasful commentedon Nov 2, 2021
@FabiEbert Hello, yeah that's what I ended up doing. But I don't feel like is the cleaner way you know. Also, if you want the slug to be updated each time you update the title you need to add this in your model
dandiep commentedon Dec 8, 2021
Any other thoughts on how to actually use the computed_property() from SQL alchemy? E.g.
This results in in "column Parent.child_count does not exist."
angel007sya commentedon Feb 10, 2022
Related to this issue #240
figaro-smartotum commentedon May 30, 2023
I think this is one of biggest SQLModel drawbacks I've encountered.
I tried the root-validator approach (which needs
validate_assignment=Truein order to get the computer column properly updated), but the root validator method is sometime invoked with an incomplete dict (having the additional_sa_instance_statefield, but without other required fields such asrequired_field1in the example below).I am trying to use the root validator in a 'mix-in' class, in order to calculate an hash-value on a subset of the model fields.
Matthieu-LAURENT39 commentedon Jul 21, 2023
Pydantic v2.0 adds support for computed fields, which should allow computed columns once Pydantic V2 support is added (related to #532, #621)
samidarko commentedon Feb 3, 2024
This worked for me
but could not do a query
Update, this is working:
ErikFub commentedon Feb 7, 2024
Workaround: Generating a dynamic property (this does NOT add a column to the database)
As @samidarko already mentioned, with pydantic 2.0's
computed_fielddecorator, you can generate a dynamic property:Result:
Note that this solution computes the 'column' each time it is accessed and does not create a new column in the database. However, when disregarding efficiency considerations, I believe that this is a good workaround for many cases.
Application to other cases
You can replace the code in
slug()with whatever your need is. You can even access relationship attributes:gavinest commentedon Feb 11, 2024
@ErikFub in your example
slugis available as a property on class but is not actually made as a column in the database table. Is that what you are seeing as well?I believe OPs original question wanted the slug field/value to be persisted to the database.
I'm using the latest sqlmodel version 0.14 and pydantic 2.0.
ErikFub commentedon Feb 11, 2024
@gavinest True that, I missed the part that it should persist in the database - thanks for pointing that out! I've adjusted my answer accordingly
50Bytes-dev commentedon Feb 14, 2024
Use my PR #801
pascalwhoop commentedon Jun 10, 2025
we want to do something similar where we have a
it would be amazing if we could simply do some form of
@computedannotation on those fields together with a function that gets as input the object and can then calculate the value which then gets returned and persisted so the next time it doesn't get re-calculatedYuriiMotov commentedon Aug 27, 2025
Thanks all for discussion!
I think this issue should be closed. Author wanted to create real column in DB that would be automatically calculated (updated) on row update.
column_propertydoesn't do that. It doesn't create real column, but just calculates the value during the query time on DB side.So, if it's strict that real column should be created, than let's start from trying to come up with the code example with pure SQLAlchemy.
If that requirement is not strict, let's start from defining requirements.
Anyway, I would suggest closing this and opening a discussion if needed.
If we understand that there is no appropriate way to achieve what is needed, we can create a feature request with clear description.