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
{{ message }}
Repository navigation
support dataclass defaults that don't affect subsequent ORM operations #12168
The use case for this is mainly dataclass defaults, so that we can use mapped_column(default=<new-constrant-here>) and that's equivalent to not setting the field at all.
This should also work for relationships:
Some considerations from other discussions:
i think one area that we have a choice to make is if you have an object with state and you say, myobject.foo = NO_VALUE - does that expire the attribute or just do nothing? I vote for the latter #12165 (reply in thread)
In the above example either behaviour is fine.
Not sure if before assert thing.foo == 'bar' in the first example 'foo' should be in the expired_attributes or not. I trust your insight here if you prefer for not. #12165 (reply in thread)
myobject.foo = NO_VALUE - does that expire the attribute or just do nothing
Another case:
thing=session.get(Thing, 1)
assertthing.foo=='bar'thing.foo='new-value'thing.foo=NO_VALUE# assert thing.foo == 'bar' # this would again passsession.commit() # nothing to do here. No update is done, new-value is lost
Here I think the correct behaviour would be to ignore the set of new-value, so I would go for expire, since I'm not sure if it can be done without expiring the field. If we can do that that I'm back ad no preference
changed the title [-]Add a magic value for the ORM to indicate that no-value is being set.[/-][+]Add a constant for the ORM to indicate that no-value is being set.[/+]on Dec 9, 2024
what it means is that making a UserMappedModel will not actually populate None into __dict__ if not passed, that is, it still is using DONT_SET above, you just dont see it.
stealth_default could set up an event to support other kinds of defaults too other than None, this is what init_scalar supports
here is that
from __future__ importannotationsfromsqlalchemyimportcreate_enginefromsqlalchemyimporteventfromsqlalchemyimportForeignKeyfromsqlalchemy.ormimportDeclarativeBasefromsqlalchemy.ormimportMappedfromsqlalchemy.ormimportmapped_columnfromsqlalchemy.ormimportrelationshipfromsqlalchemy.ormimportSession, MappedAsDataclassfromsqlalchemy.orm.attributesimportDONT_SETfromtypingimportTYPE_CHECKINGclassBase(DeclarativeBase):
passclassUserMappedModel(MappedAsDataclass, Base):
__tablename__="user"id: Mapped[int] =mapped_column(primary_key=True)
name: Mapped[str]
ifTYPE_CHECKING:
# what the API would bestatus: Mapped[str] =mapped_column(default="default_status", stealth_default=True)
else:
# what actually happens, part Istatus: Mapped[str] =mapped_column(default=DONT_SET)
# what actually happens, part II@event.listens_for(UserMappedModel.status, "init_scalar", retval=True)defreceive_init_scalar(target, value, dict_):
return"default_status"e=create_engine("sqlite://")
Base.metadata.create_all(e)
session=Session(e)
user=UserMappedModel(id=1, name="Jon", status="active")
session.merge(user)
session.commit()
user=UserMappedModel(id=1, name="John")
assertuser.status=="default_status"new_user=session.merge(user)
session.commit()
print(new_user)
I'm -1 on doing that under the hood, but that new argument may make sense to add. But I think it's better to just pass to it the value while keeping default as is.
So something like mapped_column(default=UNSET, new_argument="default_status")
это означает, что создание UserMappedModelволи фактически не заполнит Noneполе __dict__if not passed, то есть оно все равно используется DONT_SETвыше, вы просто его не видите.
stealth_default может настроить событие для поддержки других типов значений по умолчанию None, кроме того, что поддерживает init_scalar
вот это
from __future__ importannotationsfromsqlalchemyimportcreate_enginefromsqlalchemyimporteventfromsqlalchemyimportForeignKeyfromsqlalchemy.ormimportDeclarativeBasefromsqlalchemy.ormimportMappedfromsqlalchemy.ormimportmapped_columnfromsqlalchemy.ormimportrelationshipfromsqlalchemy.ormimportSession, MappedAsDataclassfromsqlalchemy.orm.attributesimportDONT_SETfromtypingimportTYPE_CHECKINGclassBase(DeclarativeBase):
passclassUserMappedModel(MappedAsDataclass, Base):
__tablename__="user"id: Mapped[int] =mapped_column(primary_key=True)
name: Mapped[str]
ifTYPE_CHECKING:
# what the API would bestatus: Mapped[str] =mapped_column(default="default_status", stealth_default=True)
else:
# what actually happens, part Istatus: Mapped[str] =mapped_column(default=DONT_SET)
# what actually happens, part II@event.listens_for(UserMappedModel.status, "init_scalar", retval=True)defreceive_init_scalar(target, value, dict_):
return"default_status"e=create_engine("sqlite://")
Base.metadata.create_all(e)
session=Session(e)
user=UserMappedModel(id=1, name="Jon", status="active")
session.merge(user)
session.commit()
user=UserMappedModel(id=1, name="John")
assertuser.status=="default_status"new_user=session.merge(user)
session.commit()
print(new_user)
looks a little strange and not obvious.
I think it's worth striving for standard model behavior, regardless of whether MappedAsDataclass is used or not.
adding event.listens_for is not obvious and different behavior from the base model.
It seems to me that it is worth finalizing this proposed solution #12165 (reply in thread), because... it is more obvious and can be hidden in alchemy so that users do not have to learn a new approach to alchemy, which is already not obvious in many places
fromsqlalchemyimportForeignKey, create_enginefromsqlalchemy.ormimport (
DeclarativeBase,
Mapped,
MappedAsDataclass,
Session,
mapped_column,
relationship,
)
# Create engineengine=create_engine("sqlite:///:memory:") # echo=TrueclassBase(MappedAsDataclass, DeclarativeBase, kw_only=True):
passclassParent(Base):
__tablename__="parents"id: Mapped[int] =mapped_column(primary_key=True, init=False)
name: Mapped[str]
children: Mapped[list["Child"]] =relationship(
back_populates="parent",
cascade="all, delete-orphan",
default_factory=list, # Using `init=False` instead will result in 2 children, even after merge
)
classChild(Base):
__tablename__="children"id: Mapped[int] =mapped_column(primary_key=True, init=False)
name: Mapped[str]
parent_id: Mapped[int] =mapped_column(
ForeignKey("parents.id", ondelete="CASCADE"), init=False
)
parent: Mapped[Parent] =relationship(
back_populates="children", init=False
)
Base.metadata.create_all(engine)
# Create a parent with some children.withSession(engine) assession:
# Create a parent with two childrenparent=Parent(name="Parent1")
parent.children.append(Child(name="Child1"))
parent.children.append(Child(name="Child2"))
session.add(parent)
session.commit()
print("Original parent child count:", len(parent.children)) # 2# When merging in a new Parent instance with the same ID, the `default_factory=list` causes the# attribute to be "loaded", leading all children to be deleted.withSession(engine) assession:
new_parent=Parent(name="Parent1")
new_parent.id=parent.idmerged_parent=session.merge(new_parent)
# After merging, the children will be deleted due to the default_factory.print("Child count after merge:", len(merged_parent.children)) # 0!
Activity
CaselIT commentedon Dec 9, 2024
I prefer
UNSETcompared withNO_VALUEas a word, but overall they mean probably the same thingCaselIT commentedon Dec 9, 2024
Another case:
Here I think the correct behaviour would be to ignore the set of new-value, so I would go for expire, since I'm not sure if it can be done without expiring the field. If we can do that that I'm back ad no preference
[-]Add a magic value for the ORM to indicate that no-value is being set.[/-][+]Add a constant for the ORM to indicate that no-value is being set.[/+]zzzeek commentedon Dec 9, 2024
as mentioned elsewhere there's not a great way to type this
if you say
That's going to fail typing, would have to be like
unless if we typed DONTSET as None .....
zzzeek commentedon Dec 9, 2024
so that typing looks like:
we also have a way to customize that default "scalar get" value which is little used : https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.AttributeEvents.init_scalar
to use that, someone would need to make another DONTSET of their own, like:
zzzeek commentedon Dec 9, 2024
maybe we have a bunch of them canned for typical defaults
zzzeek commentedon Dec 9, 2024
this does the basic thing
demo
there can be the possibility of doing more with the init_scalar event and having this
Nonebe more customizableCaselIT commentedon Dec 9, 2024
We can just type this as Any. That eliminates any typing issue
zzzeek commentedon Dec 9, 2024
@n-leonovets I can see doing the above pattern, integrating
init_scalar, and having the two flags such as:what it means is that making a
UserMappedModelwill not actually populateNoneinto__dict__if not passed, that is, it still is usingDONT_SETabove, you just dont see it.stealth_default could set up an event to support other kinds of defaults too other than
None, this is what init_scalar supportshere is that
CaselIT commentedon Dec 9, 2024
I'm -1 on doing that under the hood, but that new argument may make sense to add. But I think it's better to just pass to it the value while keeping default as is.
So something like
mapped_column(default=UNSET, new_argument="default_status")nleononline commentedon Dec 10, 2024
looks a little strange and not obvious.
I think it's worth striving for standard model behavior, regardless of whether MappedAsDataclass is used or not.
adding event.listens_for is not obvious and different behavior from the base model.
It seems to me that it is worth finalizing this proposed solution #12165 (reply in thread), because... it is more obvious and can be hidden in alchemy so that users do not have to learn a new approach to alchemy, which is already not obvious in many places
24 remaining items
zzzeek commentedon May 19, 2025
Here is a custom base that solves the problem for 2.0
POC
zzzeek commentedon Jun 20, 2025
we're going to expand this to include default_factory with collection-based relationship
zzzeek commentedon Jun 20, 2025
here's the mcve for the relationship case
sqla-tester commentedon Jun 20, 2025
Mike Bayer has proposed a fix for this issue in the main branch:
Extend #12168 to relationship collections https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/5977
Merge "Extend #12168 to relationship collections" into main
Extend sqlalchemy#12168 to relationship collections
Extend sqlalchemy#12168 to relationship collections
fix: WriteOnlyMapped + MappedAsDataclass compatibility in 2.1
accept plain collection type for relationship default_factory
flush dataclass defaults for use_existing_column
accept plain collection type for function collection_class