Repository navigation
Description
Describe the bug
Reflex infers every scalar SQLAlchemy relationship as optional, even when the relationship is declared Mapped[Profile] and backed by a non-nullable foreign key. This gives state Vars a type that contradicts the model's annotation and database constraint.
To Reproduce
import reflex as rx
from sqlalchemy import ForeignKey
from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, mapped_column, relationship
from reflex_base.utils.types import get_attribute_access_type
class Base(MappedAsDataclass, DeclarativeBase):
pass
class Profile(Base):
__tablename__ = "profile"
id: Mapped[int] = mapped_column(init=False, primary_key=True)
name: Mapped[str]
class User(Base):
__tablename__ = "user"
id: Mapped[int] = mapped_column(init=False, primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey("profile.id"), init=False)
profile: Mapped[Profile] = relationship()
print(User.__table__.c.profile_id.nullable) # False
print(get_attribute_access_type(User, "profile")) # Profile | None, unexpectedlyOn current upstream, a state Var for User.profile is likewise typed as Profile | None even though Mapped[Profile] and the non-nullable FK make the relationship required. The relationship handling in get_attribute_access_type returns type_ | None unconditionally whenever uselist is false.
Expected behavior
Infer scalar relationship nullability from the mapped annotation and/or relationship columns: a required Mapped[Profile] relationship should remain Profile, while an explicitly optional Mapped[Profile | None] relationship should remain optional.
Specifics
- Verified on current upstream
main(6f5c39cac). - The relevant branch is in
packages/reflex-base/src/reflex_base/utils/types.py, inget_attribute_access_typefor SQLAlchemyRelationshipdescriptors.
Additional context
This is distinct from #8043, which concerns AssociationProxyInstance values being inferred as lists. It is also separate from #7831/#7756, which concern runtime SQLAlchemy model serialization and hybrid properties. The current relationship branch has a TODO to check nullability; I found no issue or open PR specifically covering required-vs-optional scalar relationship Var types.
Activity
linear-code commentedon Nov 28, 2026
ENG-15086