I have a SQLAlchemy model like this:
class User(db.Model):
id: Mapped[int] = mapped_column(primary_key=True)
column: Mapped[int] = mapped_column(nullable=True, unique=True)
How can I make it so column
column can be null, and will be an autoincremented integer value otherwise?
user1 = User() # here the `column` should be null
user2 = User() # missing code to make `column` autoincremented value, so for example if the previous user had it as NULL here it would be the first value, 0
I am using PostgreSQL and Flask-SQLAlchemy if this helps.
I have a SQLAlchemy model like this:
class User(db.Model):
id: Mapped[int] = mapped_column(primary_key=True)
column: Mapped[int] = mapped_column(nullable=True, unique=True)
How can I make it so column
column can be null, and will be an autoincremented integer value otherwise?
user1 = User() # here the `column` should be null
user2 = User() # missing code to make `column` autoincremented value, so for example if the previous user had it as NULL here it would be the first value, 0
I am using PostgreSQL and Flask-SQLAlchemy if this helps.
Share Improve this question asked Feb 17 at 15:18 roundedrectangleroundedrectangle 13 bronze badges New contributor roundedrectangle is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 6 | Show 1 more comment2 Answers
Reset to default 0Thanks to @MatsLindh who recommended a better solution:
from sqlalchemy import Sequence
seq = Sequence('user_column_seq', optional=True)
class User(db.Model):
id: Mapped[int] = mapped_column(primary_key=True)
column: Mapped[int] = mapped_column(nullable=True, unique=True)
user1 = User() # NULL
user2 = User(column=seq.next_value()) # next free value
UPD: see the better answer based on @MatsLindh's comment
This is not a complete answer to the question but a workaround I found and will use.
This is what I came up with:
from sqlalchemy import func
# tip: this can be decorated as a @property in a class
def next_value():
v = User.query.with_entities(func.max(User.column)).scalar()
return v+1 if v is not None else 0
Usage:
user1 = User() # NULL
user2 = User(column=next_value()) # next free value
not null
andunique
. I do not know if Flask-SQLAchmy will accept the above but the database would not. – Belayer Commented Feb 17 at 18:30primary_key
is set to True,nullable=False
andunique=False
parameters are set like so automatically. This is not only for Flask-SQLAlchemy, but for vanilla SQLAlchemy too. – roundedrectangle Commented Feb 17 at 19:18username
, and I want user to be able to choose to have a username or a special number. I don't want users with username to have that number, thus I want that column to be nullable. The number should be choosen by the next free one available, which is why I need autoincrement. – roundedrectangle Commented Feb 18 at 7:08