Skip to content

Contrib: SQLAlchemy

Full attribute and method reference for the SQLAlchemy backend (starlette_admin.contrib.sqla), generated from docstrings. For a task-oriented walkthrough, see SQLAlchemy.

starlette_admin.contrib.sqla.admin.Admin

Bases: BaseAdmin

Source code in starlette_admin/contrib/sqla/admin.py
class Admin(BaseAdmin):
    def __init__(
        self,
        session_provider: SessionProvider,
        title: str = _("Admin"),
        base_url: str = "/admin",
        route_name: str = "admin",
        logo_url: str | Callable[[Request], str | None] | None = None,
        login_logo_url: str | Callable[[Request], str | None] | None = None,
        favicon_url: str | Callable[[Request], str | None] | None = None,
        templates_dir: str = "templates",
        additional_loaders: Sequence[BaseLoader] | None = None,
        static_dir: str | None = None,
        index_view: CustomView | None = None,
        theme: BaseTheme | None = None,
        auth_provider: BaseAuthProvider | None = None,
        secret_key: str | None = None,
        middlewares: Sequence[Middleware] | None = None,
        i18n_config: I18nConfig | None = None,
        timezone_config: TimezoneConfig | None = TimezoneConfig(),
        import_config: ImportConfig | None = None,
        export_config: ExportConfig | None = None,
        plugins: Sequence[BasePlugin] | None = None,
        debug: bool = False,
    ) -> None:
        super().__init__(
            title=title,
            base_url=base_url,
            route_name=route_name,
            logo_url=logo_url,
            login_logo_url=login_logo_url,
            favicon_url=favicon_url,
            templates_dir=templates_dir,
            additional_loaders=additional_loaders,
            static_dir=static_dir,
            index_view=index_view,
            theme=theme,
            auth_provider=auth_provider,
            secret_key=secret_key,
            middlewares=middlewares,
            i18n_config=i18n_config,
            timezone_config=timezone_config,
            import_config=import_config,
            export_config=export_config,
            plugins=plugins,
            debug=debug,
        )
        self.middlewares = [] if self.middlewares is None else list(self.middlewares)
        self.middlewares.insert(
            0, Middleware(DBSessionMiddleware, session_provider=session_provider)
        )
        engine_type = "async" if is_async_session_provider(session_provider) else "sync"
        source = (
            "sessionmaker"
            if isinstance(session_provider, (sessionmaker, async_sessionmaker))
            else "engine"
        )
        _log.info(
            "Admin initialized (engine=%s, source=%s, base_url=%r)",
            engine_type,
            source,
            base_url,
        )

    def mount_to(self, app: Starlette) -> None:
        _log.info("Mounting Admin to app at %r", self.base_url)
        try:
            # If sqlalchemy_file is installed, register the route that serves
            # its stored files.
            __import__("sqlalchemy_file")
            self.routes.append(
                Route(
                    "/_api/file/{storage}/{file_id}",
                    _serve_file,
                    methods=["GET"],
                    name="api:file",
                )
            )
            _log.debug("sqlalchemy_file detected, registered file-serving route")
        except ImportError:  # pragma: no cover
            pass
        super().mount_to(app)

starlette_admin.contrib.sqla.view.ModelView

Bases: BaseModelView

A view for managing SQLAlchemy models.

Source code in starlette_admin/contrib/sqla/view.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
class ModelView(BaseModelView):
    """A view for managing SQLAlchemy models."""

    sortable_field_mapping: ClassVar[dict[str, InstrumentedAttribute]] = {}
    """A dictionary for overriding the default model attribute used for sorting.

    Example:
        ```python
        class Post(Base):
            __tablename__ = "post"

            id: Mapped[int] = mapped_column(primary_key=True)
            title: Mapped[str] = mapped_column()
            user_id: Mapped[int] = mapped_column(ForeignKey("user.id"))
            user: Mapped[User] = relationship(back_populates="posts")


        class PostView(ModelView):
            sortable_field = ["id", "title", "user"]
            sortable_field_mapping = {
                "user": User.age,  # Sort by the age of the related user
            }
        ```
    """

    def __init__(
        self,
        model: type[Any],
        icon: str | None = None,
        display_name: str | None = None,
        menu_label: str | None = None,
        key: str | None = None,
        converter: BaseSQLAModelConverter | None = None,
    ):
        _log.debug("Initializing ModelView for model %s", model.__name__)
        try:
            mapper: Mapper = inspect(model)
        except NoInspectionAvailable:
            _log.error("Class %s is not a SQLAlchemy model", model.__name__)
            raise InvalidModelError(  # noqa B904
                f"Class {model.__name__} is not a SQLAlchemy model."
            )
        self.model = model
        self.key = key or self.key or slugify_class_name(self.model.__name__)
        self.menu_label = (
            menu_label
            or self.menu_label
            or prettify_class_name(self.model.__name__) + "s"
        )
        self.display_name = (
            display_name
            or self.display_name
            or prettify_class_name(self.model.__name__)
        )
        self.icon = icon or self.icon
        explicit_fields = self.fields is not None and len(self.fields) > 0
        if not explicit_fields:
            self.fields = [
                self.model.__dict__[f].key
                for f in list(self.model.__dict__.keys())
                if type(self.model.__dict__[f]) is InstrumentedAttribute
            ]
        self.fields = (converter or ModelConverter()).convert_fields_list(
            fields=self.fields,
            model=self.model,
            mapper=mapper,
            explicit_fields=explicit_fields,
        )
        self._columns: set[str] = {attr.key for attr in mapper.column_attrs}
        self._setup_primary_key()
        self.exclude_fields_from_list = (
            normalize_list(self.exclude_fields_from_list) or []
        )
        self.exclude_fields_from_detail = (
            normalize_list(self.exclude_fields_from_detail) or []
        )
        self.exclude_fields_from_create = (
            normalize_list(self.exclude_fields_from_create) or []
        )
        self.exclude_fields_from_edit = (
            normalize_list(self.exclude_fields_from_edit) or []
        )
        self.exclude_fields_from_export = (
            normalize_list(self.exclude_fields_from_export) or []
        )
        self.exclude_fields_from_import = (
            normalize_list(self.exclude_fields_from_import) or []
        )
        _default_list = [
            field.name
            for field in self.fields
            if not isinstance(field, (RelationField, FileField))
        ]
        self.searchable_fields = normalize_list(
            self.searchable_fields
            if (self.searchable_fields is not None)
            else _default_list
        )
        self.sortable_fields = normalize_list(
            self.sortable_fields
            if (self.sortable_fields is not None)
            else _default_list
        )
        self.fields_default_sort = normalize_list(
            self.fields_default_sort, is_default_sort_list=True
        )
        super().__init__()
        _log.info(
            "ModelView for %s registered (key=%r, pk=%s, %d field(s))",
            self.model.__name__,
            self.key,
            self.pk_attr,
            len(self.fields),
        )

    def _setup_primary_key(self) -> None:
        # Detect the model's primary key attribute(s).
        _pk_attrs = []
        self._pk_column: tuple[InstrumentedAttribute, ...] | InstrumentedAttribute = ()
        self._pk_coerce: tuple[type, ...] | type = ()
        for key in list(self.model.__dict__.keys()):
            attr = getattr(self.model, key)
            if isinstance(attr, InstrumentedAttribute) and getattr(
                attr, "primary_key", False
            ):
                _pk_attrs.append(key)
        _log.debug(
            "Primary key detection for %s: found %s",
            self.model.__name__,
            _pk_attrs,
        )
        if len(_pk_attrs) > 1:
            _log.debug("Composite PK for %s: %s", self.model.__name__, _pk_attrs)
            self._pk_column = tuple(getattr(self.model, attr) for attr in _pk_attrs)
            self._pk_coerce = tuple(
                extract_column_python_type(c) for c in self._pk_column
            )
            self.pk_field: BaseField = MultiplePKField(_pk_attrs)
        else:
            assert len(_pk_attrs) == 1, (
                f"No primary key found in model {self.model.__name__}"
            )
            self._pk_column = getattr(self.model, _pk_attrs[0])
            self._pk_coerce = extract_column_python_type(self._pk_column)  # type: ignore[arg-type]
            try:
                # Reuse the already-converted field if the PK is declared.
                self.pk_field = next(f for f in self.fields if f.name == _pk_attrs[0])
            except StopIteration:
                # The PK is not among the declared fields, so fall back to
                # treating its value as a plain string.
                _log.warning(
                    "%s: PK field %r not in declared fields, falling back to StringField",
                    self.model.__name__,
                    _pk_attrs[0],
                )
                self.pk_field = StringField(_pk_attrs[0])
        self.pk_attr = self.pk_field.name

    async def handle_action(
        self, request: Request, selection: ActionSelection, name: str
    ) -> None | Response:
        try:
            return await super().handle_action(request, selection, name)
        except SQLAlchemyError as exc:
            _log.error(
                "SQLAlchemyError in action %r (model=%s): %s",
                name,
                self.model.__name__,
                exc,
                exc_info=True,
            )
            raise ActionFailed(str(exc)) from exc

    async def handle_row_action(
        self, request: Request, pk: Any, name: str
    ) -> None | Response:
        try:
            return await super().handle_row_action(request, pk, name)
        except SQLAlchemyError as exc:
            _log.error(
                "SQLAlchemyError in row action %r (model=%s, pk=%r): %s",
                name,
                self.model.__name__,
                pk,
                exc,
                exc_info=True,
            )
            raise ActionFailed(str(exc)) from exc

    def get_detail_query(self, request: Request) -> Select:
        """Return the base `Select` statement used by
        [find_by_pk][starlette_admin.views.BaseModelView.find_by_pk] and
        [find_by_pks][starlette_admin.views.BaseModelView.find_by_pks].

        Defaults to [get_list_query][starlette_admin.contrib.sqla.ModelView.get_list_query]
        so overrides of the latter (e.g. eager loading options) also apply
        to the detail view.

        Examples:
            ```python  hl_lines="3-4"
            class PostView(ModelView):

                    def get_detail_query(self, request: Request):
                        return super().get_detail_query(request).options(selectinload(Post.author))
            ```
        """
        return self.get_list_query(request)

    def get_list_query(self, request: Request) -> Select:
        """Return the base `Select` statement used by
        [find_all][starlette_admin.views.BaseModelView.find_all].

        Examples:
            ```python  hl_lines="3-4"
            class PostView(ModelView):

                    def get_list_query(self, request: Request):
                        return super().get_list_query().where(Post.published == true())

                    def get_count_query(self, request: Request):
                        return super().get_count_query().where(Post.published == true())
            ```

        If you override this method, also override
        [get_count_query][starlette_admin.contrib.sqla.ModelView.get_count_query]
        so the list view displays the correct item count.
        """
        return select(self.model)

    def get_count_query(self, request: Request) -> Select:
        """Return the base `Select` statement used by
        [count][starlette_admin.views.BaseModelView.count].

        Examples:
            ```python hl_lines="6-7"
            class PostView(ModelView):

                    def get_list_query(self, request: Request):
                        return super().get_list_query().where(Post.published == true())

                    def get_count_query(self, request: Request):
                        return super().get_count_query().where(Post.published == true())
            ```
        """
        return select(func.count()).select_from(self.model)

    def get_search_query(self, request: Request, term: str) -> Any:
        """Return the SQLAlchemy WHERE clause used for full-text search.

        Parameters:
           request: The request being processed.
           term: The search term entered by the user.

        Examples:
           ```python
           class PostView(ModelView):

                def get_search_query(self, request: Request, term: str):
                    return Post.title.contains(term)
           ```
        """
        clauses = []
        for field in self.get_fields_list(request):
            if field.searchable and type(field) in [
                StringField,
                SlugField,
                TextAreaField,
                EmailField,
                URLField,
                PhoneField,
                ColorField,
                EnumField,
            ]:
                attr = getattr(self.model, field.name)
                clauses.append(cast(attr, String).ilike(f"%{term}%"))
        return or_(*clauses)

    def get_filter_registry(self) -> FilterRegistry:
        """Return the [FilterRegistry][starlette_admin.filters.FilterRegistry]
        of concrete SQLAlchemy filter implementations
        (`starlette_admin.contrib.sqla.filters`) used to determine which
        filters are available for each field on this view's list page.
        """
        return SqlaFilterRegistry()

    async def _apply_search_and_filters(
        self,
        request: Request,
        stmt: Select,
        q: str | None,
        filters: FilterGroup | None,
    ) -> Select:
        if q is not None:
            _log.debug("Applying full-text search q=%r to %s", q, self.model.__name__)
            stmt = stmt.where(
                await self.build_full_text_search_query(request, q, self.model)
            )
        if filters is not None and not filters.is_empty():
            _log.debug("Applying filter group to %s", self.model.__name__)
            fields_by_name = {f.name: f for f in self.get_fields_list(request)}
            clause = build_filter_clause(
                filters, fields_by_name, self.get_filter_registry(), self, request
            )
            if clause is not None:
                stmt = stmt.where(clause)
        return stmt

    async def count(
        self,
        request: Request,
        q: str | None = None,
        filters: FilterGroup | None = None,
    ) -> int:
        _log.debug(
            "count %s (q=%r, has_filters=%s)",
            self.model.__name__,
            q,
            filters is not None and not filters.is_empty(),
        )
        session: Session | AsyncSession = request.state.session
        stmt = await self._apply_search_and_filters(
            request, self.get_count_query(request), q, filters
        )
        if isinstance(session, AsyncSession):
            n = (await session.execute(stmt)).scalar_one()
        else:
            n = (await anyio.to_thread.run_sync(session.execute, stmt)).scalar_one()
        _log.debug("count %s → %d", self.model.__name__, n)
        return n

    async def find_all(
        self,
        request: Request,
        skip: int = 0,
        limit: int = 100,
        q: str | None = None,
        sorts: Sequence[tuple[str, str]] | None = None,
        filters: FilterGroup | None = None,
    ) -> Sequence[Any]:
        _log.debug(
            "find_all %s (skip=%d, limit=%d, q=%r, sorts=%r)",
            self.model.__name__,
            skip,
            limit,
            q,
            sorts,
        )
        session: Session | AsyncSession = request.state.session
        stmt = self.get_list_query(request).offset(skip)
        if limit > 0:
            stmt = stmt.limit(limit)
        stmt = await self._apply_search_and_filters(request, stmt, q, filters)
        stmt = self.build_order_clauses(request, sorts or [], stmt)
        for field in self.get_fields_list(request):
            if isinstance(field, RelationField):
                stmt = stmt.options(joinedload(getattr(self.model, field.name)))
        if isinstance(session, AsyncSession):
            rows = (await session.execute(stmt)).scalars().unique().all()
        else:
            rows = (
                (await anyio.to_thread.run_sync(session.execute, stmt))
                .scalars()
                .unique()
                .all()
            )
        _log.debug("find_all %s → %d row(s)", self.model.__name__, len(rows))
        return rows

    async def find_by_pk(self, request: Request, pk: Any) -> Any:
        _log.debug("find_by_pk %s pk=%r", self.model.__name__, pk)
        session: Session | AsyncSession = request.state.session
        if isinstance(self._pk_column, tuple):
            # For a composite primary key, `pk` is a comma-separated string
            # of each primary key attribute's value. For a model with two
            # primary keys (id1, id2), `pk` is "val1,val2" and the generated
            # clause is (id1 == val1 AND id2 == val2).
            assert isinstance(self._pk_coerce, tuple)
            clause = and_(
                *(
                    (
                        _pk_col == _coerce(_pk)
                        if _coerce is not bool
                        # bool("False") is True, so compare the decoded string directly.
                        else _pk_col == (_pk == "True")
                    )
                    for _pk_col, _coerce, _pk in zip(
                        self._pk_column,
                        self._pk_coerce,
                        iterdecode(pk),
                    )
                )
            )
        else:
            assert isinstance(self._pk_coerce, type)
            clause = self._pk_column == self._pk_coerce(pk)
        stmt = self.get_detail_query(request).where(clause)
        for field in self.get_fields_list(request):
            if isinstance(field, RelationField):
                stmt = stmt.options(joinedload(getattr(self.model, field.name)))
        if isinstance(session, AsyncSession):
            obj = (await session.execute(stmt)).scalars().unique().one_or_none()
        else:
            obj = (
                (await anyio.to_thread.run_sync(session.execute, stmt))
                .scalars()
                .unique()
                .one_or_none()
            )
        if obj is None:
            _log.warning("find_by_pk %s pk=%r → not found", self.model.__name__, pk)
        return obj

    async def find_by_pks(self, request: Request, pks: list[Any]) -> Sequence[Any]:
        _log.debug("find_by_pks %s: %d pk(s)", self.model.__name__, len(pks))
        has_multiple_pks = isinstance(self._pk_column, tuple)
        try:
            return await self._exec_find_by_pks(request, pks)
        except DBAPIError:  # pragma: no cover
            if has_multiple_pks:
                # The composite IN construct can fail on backends that don't
                # support it; retry with an equivalent OR-of-ANDs clause.
                # Not covered by the test suite: SQLite, MySQL, and
                # PostgreSQL all support the composite IN construct.
                _log.warning(
                    "find_by_pks %s: composite IN failed (DBAPIError), retrying with OR clauses",
                    self.model.__name__,
                )
                return await self._exec_find_by_pks(request, pks, False)
            raise

    async def _exec_find_by_pks(
        self, request: Request, pks: list[Any], use_composite_in: bool = True
    ) -> Sequence[Any]:
        session: Session | AsyncSession = request.state.session

        if isinstance(self._pk_column, tuple):
            # Composite primary key: build a multi-column WHERE clause.
            clause = await self._get_multiple_pks_in_clause(pks, use_composite_in)
        else:
            assert isinstance(self._pk_coerce, type)
            clause = self._pk_column.in_(map(self._pk_coerce, pks))
        stmt = self.get_detail_query(request).where(clause)
        for field in self.get_fields_list(request):
            if isinstance(field, RelationField):
                stmt = stmt.options(joinedload(getattr(self.model, field.name)))
        if isinstance(session, AsyncSession):
            return (await session.execute(stmt)).scalars().unique().all()
        return (
            (await anyio.to_thread.run_sync(session.execute, stmt))
            .scalars()
            .unique()
            .all()
        )

    async def _get_multiple_pks_in_clause(
        self, pks: list[Any], use_composite_in: bool
    ) -> Any:
        """Build the WHERE clause for a model with a composite primary key.

        Parameters:
            pks: Comma-separated primary key values, e.g.
                `["val1,val2", "val3,val4"]` for a model with two PK columns.
            use_composite_in: If `True`, build the clause with SQLAlchemy's
                composite IN construct: `WHERE (id1, id2) IN ((val1, val2),
                (val3, val4))`. Not all database backends support this (see
                https://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.tuple_).
                If `False`, build the equivalent OR-of-ANDs clause instead:
                `WHERE (id1 == val1 AND id2 == val2) OR (id1 == val3 AND
                id2 == val4)`.
        """
        assert isinstance(self._pk_coerce, tuple)
        assert isinstance(self._pk_column, tuple)
        decoded_pks = tuple(iterdecode(pk) for pk in pks)
        if use_composite_in:
            return tuple_(*self._pk_column).in_(
                tuple(
                    (_coerce(_pk) if _coerce is not bool else _pk == "True")
                    for _coerce, _pk in zip(
                        self._pk_coerce,
                        decoded_pk,
                    )
                )
                for decoded_pk in decoded_pks
            )
        else:  # noqa: RET505, pragma: no cover
            clauses = []
            for decoded_pk in decoded_pks:
                clauses.append(
                    and_(
                        *(
                            (
                                _pk_col == _coerce(_pk)
                                if _coerce is not bool
                                # bool("False") is True, so compare the decoded string directly.
                                else (_pk_col == (_pk == "True"))
                            )
                            for _pk_col, _coerce, _pk in zip(
                                self._pk_column,
                                self._pk_coerce,
                                decoded_pk,
                            )
                        )
                    )
                )
            return or_(*clauses)

    def _refresh_attr_names(self, request: Request) -> list[str]:
        """Column attributes to reload after a create or edit flush."""
        return [
            field.name
            for field in self.get_fields_list(request)
            if field.name in self._columns
        ]

    async def create(self, request: Request, data: dict[str, Any]) -> Any:
        _log.debug("create %s: arranging and validating data", self.model.__name__)
        session: Session | AsyncSession = request.state.session
        try:
            data = await self._arrange_data(request, data)
            await self.validate(request, data)
            if isinstance(session, AsyncSession):
                async with session.begin_nested():
                    obj = await self._populate_obj(request, self.model(), data)
                    await self._emit_before_create(request, data, obj)
                    session.add(obj)
                    await session.flush()
                await session.refresh(obj, self._refresh_attr_names(request))
            else:
                with session.begin_nested():
                    obj = await self._populate_obj(request, self.model(), data)
                    await self._emit_before_create(request, data, obj)
                    session.add(obj)
                    await anyio.to_thread.run_sync(session.flush)
                await anyio.to_thread.run_sync(
                    session.refresh, obj, self._refresh_attr_names(request)
                )
            await self._emit_after_create(request, obj)
            on_commit(
                request,
                lambda: self._emit_after_create_committed(request, obj),
            )
            _log.info("Created %s", self.model.__name__)
            return obj
        except Exception as e:
            if isinstance(e, FormValidationError):
                _log.warning("create %s: validation failed: %s", self.model.__name__, e)
            else:
                _log.error(
                    "create %s: unexpected error: %s",
                    self.model.__name__,
                    e,
                    exc_info=True,
                )
            return await self.handle_exception(request, e)

    async def edit(self, request: Request, pk: Any, data: dict[str, Any]) -> Any:
        _log.debug(
            "edit %s pk=%r: arranging and validating data", self.model.__name__, pk
        )
        session: Session | AsyncSession = request.state.session
        try:
            data = await self._arrange_data(request, data, True)
            await self.validate(request, data)
            obj = await self.find_by_pk(request, pk)
            old_data = {
                f.name: getattr(obj, f.name, None)
                for f in self.get_fields_list(request)
            }
            if isinstance(session, AsyncSession):
                async with session.begin_nested():
                    await self._populate_obj(request, obj, data, True)
                    await self._emit_before_edit(
                        request, data, obj, pk=pk, old_data=old_data
                    )
                    session.add(obj)
                    await session.flush()
                await session.refresh(obj, self._refresh_attr_names(request))
            else:
                with session.begin_nested():
                    await self._populate_obj(request, obj, data, True)
                    await self._emit_before_edit(
                        request, data, obj, pk=pk, old_data=old_data
                    )
                    session.add(obj)
                    await anyio.to_thread.run_sync(session.flush)
                await anyio.to_thread.run_sync(
                    session.refresh, obj, self._refresh_attr_names(request)
                )
            await self._emit_after_edit(request, obj, pk=pk, old_data=old_data)
            on_commit(
                request,
                lambda: self._emit_after_edit_committed(
                    request, obj, old_data=old_data
                ),
            )
            _log.info("Edited %s pk=%r", self.model.__name__, pk)
            return obj
        except Exception as e:
            if isinstance(e, FormValidationError):
                _log.warning(
                    "edit %s pk=%r: validation failed: %s", self.model.__name__, pk, e
                )
            else:
                _log.error(
                    "edit %s pk=%r: unexpected error: %s",
                    self.model.__name__,
                    pk,
                    e,
                    exc_info=True,
                )
            await self.handle_exception(request, e)

    async def _arrange_data(
        self,
        request: Request,
        data: dict[str, Any],
        is_edit: bool = False,
    ) -> dict[str, Any]:
        """Return a new dict with relation fields resolved to loaded model instances.

        For each `RelationField`, replaces the submitted primary key(s) with
        the corresponding related object(s) fetched from the database.
        """
        _log.debug("_arrange_data %s (is_edit=%s)", self.model.__name__, is_edit)
        arranged_data: dict[str, Any] = {}
        for field in self.get_fields_list(request):
            if field.read_only:
                continue
            if isinstance(field, RelationField) and data[field.name] is not None:
                foreign_view = self._find_foreign_view(field.key)  # type: ignore
                if isinstance(field, HasMany):
                    # `collection_class` also allows a zero-arg factory, but this
                    # call site only ever uses it as an iterable-accepting container type.
                    arranged_data[field.name] = field.collection_class(
                        await foreign_view.find_by_pks(  # ty: ignore[too-many-positional-arguments]
                            request, data[field.name]
                        )
                    )
                else:
                    arranged_data[field.name] = await foreign_view.find_by_pk(
                        request, data[field.name]
                    )
            else:
                arranged_data[field.name] = data[field.name]
        return arranged_data

    async def _populate_obj(
        self,
        request: Request,
        obj: Any,
        data: dict[str, Any],
        is_edit: bool = False,
    ) -> Any:
        for field in self.get_fields_list(request):
            if field.read_only:
                continue
            name, value = field.name, data.get(field.name)
            if isinstance(field, FileField) and field.storage is None:
                value, should_be_deleted = not_none(value)
                if should_be_deleted:
                    setattr(obj, name, None)
                elif (not field.multiple and value is not None) or (
                    field.multiple and isinstance(value, list) and len(value) > 0
                ):
                    setattr(obj, name, value)
            else:
                setattr(obj, name, value)
        return obj

    async def delete(self, request: Request, pks: list[Any]) -> int | None:
        _log.debug("delete %s: %d pk(s): %r", self.model.__name__, len(pks), pks)
        session: Session | AsyncSession = request.state.session
        objs = await self.find_by_pks(request, pks)
        try:
            if isinstance(session, AsyncSession):
                async with session.begin_nested():
                    for obj in objs:
                        await self._emit_before_delete(
                            request, await self.get_pk_value(request, obj), obj
                        )
                        await session.delete(obj)
                    await session.flush()
            else:

                def _delete_in_savepoint() -> None:
                    with session.begin_nested():
                        for obj in objs:
                            session.delete(obj)
                        session.flush()

                for obj in objs:
                    await self._emit_before_delete(
                        request, await self.get_pk_value(request, obj), obj
                    )
                await anyio.to_thread.run_sync(_delete_in_savepoint)
        except Exception as e:  # pragma: no cover
            _log.error(
                "delete %s: unexpected error: %s",
                self.model.__name__,
                e,
                exc_info=True,
            )
            raise

        def _make_after_delete_committed(obj: Any, pk: Any) -> Callable[[], Any]:
            return lambda: self._emit_after_delete_committed(request, pk, obj)

        for obj in objs:
            pk = await self.get_pk_value(request, obj)
            await self._emit_after_delete(request, pk, obj)
            # Detach so the committed hook can still read `obj`'s already-loaded
            # attributes later: once the row is gone, a session-attached instance
            # would try to re-SELECT expired attributes on commit and raise
            # ObjectDeletedError.
            session.expunge(obj)
            on_commit(request, _make_after_delete_committed(obj, pk))
        n = len(objs)
        _log.info("Deleted %d %s record(s)", n, self.model.__name__)
        return n

    async def build_full_text_search_query(
        self, request: Request, term: str, model: Any
    ) -> Any:
        return self.get_search_query(request, term)

    def build_order_clauses(
        self,
        request: Request,
        sorts: Sequence[tuple[str, str]],
        stmt: Select,
    ) -> Select:
        for sort_by, sort_dir in sorts:
            _log.debug("Ordering %s by %r %s", self.model.__name__, sort_by, sort_dir)
            model_attr = getattr(self.model, sort_by, None)
            if model_attr is not None and isinstance(
                model_attr.property, RelationshipProperty
            ):
                stmt = stmt.outerjoin(model_attr)
            sorting_attr = self.sortable_field_mapping.get(sort_by, model_attr)
            stmt = stmt.order_by(
                not_none(sorting_attr).desc() if sort_dir == "desc" else sorting_attr
            )
        return stmt

    async def get_pk_value(self, request: Request, obj: Any) -> Any:
        return await self.pk_field.parse_obj(request, obj)

    async def get_serialized_pk_value(self, request: Request, obj: Any) -> Any:
        value = await self.get_pk_value(request, obj)
        return await self.pk_field.serialize_value(request, value)

    async def handle_exception(self, request: Request, exc: Exception) -> None:
        try:
            # Convert a sqlalchemy_file validation error into a form error,
            # if sqlalchemy_file is installed.
            from sqlalchemy_file.exceptions import ValidationError

            if isinstance(exc, ValidationError):
                raise FormValidationError({exc.key: exc.msg})
        except ImportError:  # pragma: no cover
            pass
        raise exc  # pragma: no cover

sortable_field_mapping = {} class-attribute

A dictionary for overriding the default model attribute used for sorting.

Example
class Post(Base):
    __tablename__ = "post"

    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str] = mapped_column()
    user_id: Mapped[int] = mapped_column(ForeignKey("user.id"))
    user: Mapped[User] = relationship(back_populates="posts")


class PostView(ModelView):
    sortable_field = ["id", "title", "user"]
    sortable_field_mapping = {
        "user": User.age,  # Sort by the age of the related user
    }

get_count_query(request)

Return the base Select statement used by count.

Examples:

class PostView(ModelView):

        def get_list_query(self, request: Request):
            return super().get_list_query().where(Post.published == true())

        def get_count_query(self, request: Request):
            return super().get_count_query().where(Post.published == true())
Source code in starlette_admin/contrib/sqla/view.py
def get_count_query(self, request: Request) -> Select:
    """Return the base `Select` statement used by
    [count][starlette_admin.views.BaseModelView.count].

    Examples:
        ```python hl_lines="6-7"
        class PostView(ModelView):

                def get_list_query(self, request: Request):
                    return super().get_list_query().where(Post.published == true())

                def get_count_query(self, request: Request):
                    return super().get_count_query().where(Post.published == true())
        ```
    """
    return select(func.count()).select_from(self.model)

get_detail_query(request)

Return the base Select statement used by find_by_pk and find_by_pks.

Defaults to [get_list_query][starlette_admin.contrib.sqla.ModelView.get_list_query] so overrides of the latter (e.g. eager loading options) also apply to the detail view.

Examples:

class PostView(ModelView):

        def get_detail_query(self, request: Request):
            return super().get_detail_query(request).options(selectinload(Post.author))
Source code in starlette_admin/contrib/sqla/view.py
def get_detail_query(self, request: Request) -> Select:
    """Return the base `Select` statement used by
    [find_by_pk][starlette_admin.views.BaseModelView.find_by_pk] and
    [find_by_pks][starlette_admin.views.BaseModelView.find_by_pks].

    Defaults to [get_list_query][starlette_admin.contrib.sqla.ModelView.get_list_query]
    so overrides of the latter (e.g. eager loading options) also apply
    to the detail view.

    Examples:
        ```python  hl_lines="3-4"
        class PostView(ModelView):

                def get_detail_query(self, request: Request):
                    return super().get_detail_query(request).options(selectinload(Post.author))
        ```
    """
    return self.get_list_query(request)

get_filter_registry()

Return the FilterRegistry of concrete SQLAlchemy filter implementations (starlette_admin.contrib.sqla.filters) used to determine which filters are available for each field on this view's list page.

Source code in starlette_admin/contrib/sqla/view.py
def get_filter_registry(self) -> FilterRegistry:
    """Return the [FilterRegistry][starlette_admin.filters.FilterRegistry]
    of concrete SQLAlchemy filter implementations
    (`starlette_admin.contrib.sqla.filters`) used to determine which
    filters are available for each field on this view's list page.
    """
    return SqlaFilterRegistry()

get_list_query(request)

Return the base Select statement used by find_all.

Examples:

class PostView(ModelView):

        def get_list_query(self, request: Request):
            return super().get_list_query().where(Post.published == true())

        def get_count_query(self, request: Request):
            return super().get_count_query().where(Post.published == true())

If you override this method, also override [get_count_query][starlette_admin.contrib.sqla.ModelView.get_count_query] so the list view displays the correct item count.

Source code in starlette_admin/contrib/sqla/view.py
def get_list_query(self, request: Request) -> Select:
    """Return the base `Select` statement used by
    [find_all][starlette_admin.views.BaseModelView.find_all].

    Examples:
        ```python  hl_lines="3-4"
        class PostView(ModelView):

                def get_list_query(self, request: Request):
                    return super().get_list_query().where(Post.published == true())

                def get_count_query(self, request: Request):
                    return super().get_count_query().where(Post.published == true())
        ```

    If you override this method, also override
    [get_count_query][starlette_admin.contrib.sqla.ModelView.get_count_query]
    so the list view displays the correct item count.
    """
    return select(self.model)

get_search_query(request, term)

Return the SQLAlchemy WHERE clause used for full-text search.

Parameters:

Name Type Description Default
request Request

The request being processed.

required
term str

The search term entered by the user.

required

Examples:

class PostView(ModelView):

     def get_search_query(self, request: Request, term: str):
         return Post.title.contains(term)
Source code in starlette_admin/contrib/sqla/view.py
def get_search_query(self, request: Request, term: str) -> Any:
    """Return the SQLAlchemy WHERE clause used for full-text search.

    Parameters:
       request: The request being processed.
       term: The search term entered by the user.

    Examples:
       ```python
       class PostView(ModelView):

            def get_search_query(self, request: Request, term: str):
                return Post.title.contains(term)
       ```
    """
    clauses = []
    for field in self.get_fields_list(request):
        if field.searchable and type(field) in [
            StringField,
            SlugField,
            TextAreaField,
            EmailField,
            URLField,
            PhoneField,
            ColorField,
            EnumField,
        ]:
            attr = getattr(self.model, field.name)
            clauses.append(cast(attr, String).ilike(f"%{term}%"))
    return or_(*clauses)

starlette_admin.contrib.sqla.view.InlineModelView

Bases: InlineModelView, ModelView

Inline editing of SQLAlchemy-backed related records inside a parent form.

Declare model as a class attribute. fk_attr is optional: when omitted, it is auto-detected from the SQLAlchemy relationship on the parent model (the relationship whose mapper.class_ matches model).

Set fk_attr explicitly only when auto-detection is ambiguous (multiple relationships to the same child model) or the relationship is missing:

  • Simple FK: fk_attr = "article_id"
  • Composite FK: fk_attr = ("order_store_id", "order_seq")

Example (zero config, fk_attr inferred from Article.comments):

```python
class CommentInline(InlineModelView):
    model = Comment
    fields = ["id", "author", "body"]
    extra = 2


class ArticleView(ModelView):
    inlines = [CommentInline]
```
Source code in starlette_admin/contrib/sqla/view.py
class InlineModelView(BaseInlineModelView, ModelView):
    """Inline editing of SQLAlchemy-backed related records inside a parent form.

    Declare `model` as a class attribute. `fk_attr` is optional: when omitted,
    it is auto-detected from the SQLAlchemy relationship on the parent model
    (the relationship whose `mapper.class_` matches `model`).

    Set `fk_attr` explicitly only when auto-detection is ambiguous (multiple
    relationships to the same child model) or the relationship is missing:

    - Simple FK: `fk_attr = "article_id"`
    - Composite FK: `fk_attr = ("order_store_id", "order_seq")`

    Example (zero config, `fk_attr` inferred from `Article.comments`):

        ```python
        class CommentInline(InlineModelView):
            model = Comment
            fields = ["id", "author", "body"]
            extra = 2


        class ArticleView(ModelView):
            inlines = [CommentInline]
        ```
    """

    model: ClassVar[type]  # type: ignore[misc]

    def __init__(self, parent_view: BaseModelView | None = None) -> None:
        self.parent_view = parent_view
        ModelView.__init__(self, type(self).model)

    def _get_fk_attr(self) -> str | tuple[str, ...]:
        """Return the FK attr(s), auto-detecting from the parent relationship if not set."""
        if self.fk_attr:
            return self.fk_attr
        if not hasattr(self, "_auto_fk_attr"):
            self._auto_fk_attr: str | tuple[str, ...] = (
                self._detect_fk_from_parent_relationship()
            )
        return self._auto_fk_attr

    def _detect_fk_from_parent_relationship(self) -> str | tuple[str, ...]:
        """Inspect the parent model's relationships to find the child FK column(s)."""
        if self.parent_view is None:
            raise RuntimeError(
                "Cannot auto-detect fk_attr before the inline is wired to a parent view"
            )
        parent_mapper = inspect(self.parent_view.model)  # ty: ignore[unresolved-attribute]
        child_mapper: Any = inspect(self.model)
        for rel in parent_mapper.relationships:
            if rel.mapper.class_ is not self.model:
                continue
            # synchronize_pairs = [(parent_col, child_col), ...] in definition order
            fk_keys: list[str] = []
            for _, child_col in rel.synchronize_pairs:
                for prop in child_mapper.column_attrs:
                    if child_col in prop.columns:
                        fk_keys.append(prop.key)
                        break
            if len(fk_keys) == 1:
                _log.debug(
                    "%s: auto-detected fk_attr=%r from relationship to %s",
                    type(self).__name__,
                    fk_keys[0],
                    self.parent_view.model.__name__,  # ty: ignore[unresolved-attribute]
                )
                return fk_keys[0]
            if fk_keys:
                _log.debug(
                    "%s: auto-detected composite fk_attr=%r from relationship to %s",
                    type(self).__name__,
                    tuple(fk_keys),
                    self.parent_view.model.__name__,  # ty: ignore[unresolved-attribute]
                )
                return tuple(fk_keys)
        _log.error(
            "%s: cannot auto-detect fk_attr, no relationship from %s to %s",
            type(self).__name__,
            self.parent_view.model.__name__,  # ty: ignore[unresolved-attribute]
            self.model.__name__,
        )
        raise ValueError(
            f"{type(self).__name__}: cannot auto-detect fk_attr, "
            f"no relationship from {self.parent_view.model.__name__} to "  # ty: ignore[unresolved-attribute]
            f"{self.model.__name__} found. Set fk_attr explicitly."
        )

    def _build_fk_parent_map(self) -> dict[str, str]:
        """Return `{child_fk_attr: parent_attr}` for a composite FK.

        Uses the parent's already-computed `_pk_column` to scope the column
        lookup to PK columns only.
        """
        fk_attr = self._get_fk_attr()
        assert isinstance(fk_attr, tuple)
        child_mapper: Any = inspect(self.model)

        # Restrict parent_col_map to PK columns using parent_view._pk_column
        assert self.parent_view is not None
        parent_view: ModelView = self.parent_view  # ty: ignore[invalid-assignment]
        parent_pk_cols = (
            parent_view._pk_column
            if isinstance(parent_view._pk_column, tuple)
            else (parent_view._pk_column,)
        )
        parent_mapper = inspect(parent_view.model)
        pk_col_ids = {id(col) for ia in parent_pk_cols for col in ia.property.columns}
        parent_col_map: dict[int, str] = {
            id(col): prop.key
            for prop in parent_mapper.column_attrs
            for col in prop.columns
            if id(col) in pk_col_ids
        }

        result: dict[str, str] = {}
        for attr_name in fk_attr:
            child_col = child_mapper.attrs[attr_name].columns[0]
            for fk in child_col.foreign_keys:
                result[attr_name] = parent_col_map.get(id(fk.column), fk.column.name)
                break
        return result

    async def build_fk_value(self, request: Request, parent: Any) -> Any:
        """Return the FK value(s) for a new inline row.

        For a single FK, delegates to the parent's PK value (via `pk_field`).
        For a composite FK, returns a dict mapping child FK attr to parent
        value, resolved via SQLAlchemy FK constraint introspection.
        """
        if isinstance(self._get_fk_attr(), tuple):
            return {
                child_attr: getattr(parent, parent_attr)
                for child_attr, parent_attr in self._build_fk_parent_map().items()
            }
        return await super().build_fk_value(request, parent)

    async def _arrange_data(
        self,
        request: Request,
        data: dict[str, Any],
        is_edit: bool = False,
    ) -> dict[str, Any]:
        # ModelView._arrange_data only keeps declared fields; preserve the FK
        # column(s) so _populate_obj can set them on the new object.
        fk_attr = self._get_fk_attr()
        if isinstance(fk_attr, tuple):
            fk_snapshot = {attr: data.get(attr) for attr in fk_attr}
        else:
            fk_snapshot = {fk_attr: data.get(fk_attr)}
        arranged = await super()._arrange_data(request, data, is_edit)
        if not is_edit:
            for attr, val in fk_snapshot.items():
                if val is not None:
                    arranged[attr] = val
        return arranged

    async def _populate_obj(
        self,
        request: Request,
        obj: Any,
        data: dict[str, Any],
        is_edit: bool = False,
    ) -> Any:
        await super()._populate_obj(request, obj, data, is_edit)
        if not is_edit:
            fk_attr = self._get_fk_attr()
            if isinstance(fk_attr, tuple):
                for attr in fk_attr:
                    if attr in data:
                        setattr(obj, attr, data[attr])
            elif fk_attr in data:
                setattr(obj, fk_attr, data[fk_attr])
        return obj

    async def find_by_parent(self, request: Request, parent: Any) -> Sequence[Any]:
        _log.debug(
            "find_by_parent %s: parent type=%s",
            self.model.__name__,
            type(parent).__name__,
        )
        session: Session | AsyncSession = request.state.session
        fk_attr = self._get_fk_attr()
        stmt: Any
        if isinstance(fk_attr, tuple):
            clause = and_(
                *(
                    getattr(self.model, child_attr) == getattr(parent, parent_attr)
                    for child_attr, parent_attr in self._build_fk_parent_map().items()
                )
            )
            stmt = select(self.model).where(clause)
        else:
            assert self.parent_view is not None
            parent_pk = await self.parent_view.get_pk_value(request, parent)
            fk_col = getattr(self.model, fk_attr)
            stmt = select(self.model).where(fk_col == parent_pk)
        for field in self.get_fields_list(request):
            if isinstance(field, RelationField):
                stmt = stmt.options(joinedload(getattr(self.model, field.name)))
        if isinstance(session, AsyncSession):
            rows = (await session.execute(stmt)).scalars().unique().all()
        else:
            rows = (
                (await anyio.to_thread.run_sync(session.execute, stmt))
                .scalars()
                .unique()
                .all()
            )
        _log.debug("find_by_parent %s → %d row(s)", self.model.__name__, len(rows))
        return rows

build_fk_value(request, parent) async

Return the FK value(s) for a new inline row.

For a single FK, delegates to the parent's PK value (via pk_field). For a composite FK, returns a dict mapping child FK attr to parent value, resolved via SQLAlchemy FK constraint introspection.

Source code in starlette_admin/contrib/sqla/view.py
async def build_fk_value(self, request: Request, parent: Any) -> Any:
    """Return the FK value(s) for a new inline row.

    For a single FK, delegates to the parent's PK value (via `pk_field`).
    For a composite FK, returns a dict mapping child FK attr to parent
    value, resolved via SQLAlchemy FK constraint introspection.
    """
    if isinstance(self._get_fk_attr(), tuple):
        return {
            child_attr: getattr(parent, parent_attr)
            for child_attr, parent_attr in self._build_fk_parent_map().items()
        }
    return await super().build_fk_value(request, parent)

Pydantic validation

The ext.pydantic extension validates form data against a Pydantic model before writing the record. See Pydantic validation for the full walkthrough.

starlette_admin.contrib.sqla.ext.pydantic.ModelView

Bases: ModelView

A SQLAlchemy ModelView that validates form data with a Pydantic model.

Example:

```python
from starlette_admin.contrib.sqla.ext.pydantic import ModelView


class Post(Base):
    __tablename__ = "posts"

    id = Column(Integer, primary_key=True)
    title = Column(String)
    content = Column(Text)
    views = Column(Integer)


class PostIn(BaseModel):
    id: Optional[int] = Field(primary_key=True)
    title: str = Field(min_length=3)
    content: str = Field(min_length=10)
    views: int = Field(multiple_of=4)

    @validator("title")
    def title_must_contain_space(cls, v):
        if " " not in v.strip():
            raise ValueError("title must contain a space")
        return v.title()


admin.add_view(ModelView(Post, pydantic_model=PostIn))

```
Source code in starlette_admin/contrib/sqla/ext/pydantic.py
class ModelView(BaseModelView):
    """A SQLAlchemy `ModelView` that validates form data with a Pydantic model.

    Example:

        ```python
        from starlette_admin.contrib.sqla.ext.pydantic import ModelView


        class Post(Base):
            __tablename__ = "posts"

            id = Column(Integer, primary_key=True)
            title = Column(String)
            content = Column(Text)
            views = Column(Integer)


        class PostIn(BaseModel):
            id: Optional[int] = Field(primary_key=True)
            title: str = Field(min_length=3)
            content: str = Field(min_length=10)
            views: int = Field(multiple_of=4)

            @validator("title")
            def title_must_contain_space(cls, v):
                if " " not in v.strip():
                    raise ValueError("title must contain a space")
                return v.title()


        admin.add_view(ModelView(Post, pydantic_model=PostIn))

        ```
    """

    def __init__(
        self,
        model: type[Any],
        pydantic_model: type[BaseModel],
        icon: str | None = None,
        display_name: str | None = None,
        menu_label: str | None = None,
        key: str | None = None,
        converter: BaseSQLAModelConverter | None = None,
    ):
        self.pydantic_model = pydantic_model
        super().__init__(model, icon, display_name, menu_label, key, converter)

    async def validate(self, request: Request, data: dict[str, Any]) -> None:
        try:
            self.pydantic_model(**data)
        except ValidationError as error:
            raise pydantic_error_to_form_validation_errors(error) from error

Fields

starlette_admin.contrib.sqla.fields.MultiplePKField dataclass

Bases: StringField

Virtual field to represent multiple primary keys as a single field.

This field joins the values of multiple primary key columns into a single string, encoding/decoding each value.

Source code in starlette_admin/contrib/sqla/fields.py
@dataclass(init=False)
class MultiplePKField(StringField):
    """Virtual field to represent multiple primary keys as a single field.

    This field joins the values of multiple primary key columns into a
    single string, encoding/decoding each value.
    """

    def __init__(self, pk_attrs: Sequence[str]):
        self.pk_attrs = pk_attrs
        name = ",".join(pk_attrs)
        super().__init__(
            name,
            exclude_from_list=True,
            exclude_from_detail=True,
            exclude_from_edit=True,
            exclude_from_create=True,
        )

    async def parse_obj(self, request: Request, obj: Any) -> Any:
        """Encode the object's primary key values into a single string."""
        return iterencode(str(getattr(obj, n)) for n in self.name.split(","))

parse_obj(request, obj) async

Encode the object's primary key values into a single string.

Source code in starlette_admin/contrib/sqla/fields.py
async def parse_obj(self, request: Request, obj: Any) -> Any:
    """Encode the object's primary key values into a single string."""
    return iterencode(str(getattr(obj, n)) for n in self.name.split(","))

starlette_admin.contrib.sqla.fields.FileField dataclass

Bases: FileField

A FileField that serializes values stored with sqlalchemy_file.FileField.

Source code in starlette_admin/contrib/sqla/fields.py
@dataclass
class FileField(BaseFileField):
    """A `FileField` that serializes values stored with `sqlalchemy_file.FileField`."""

    async def serialize_value(self, request: Request, value: Any) -> Any:
        try:
            return _serialize_sqlalchemy_file_library(
                request, value, request.state.action, self.multiple
            )
        except (
            ImportError,
            ModuleNotFoundError,
            NotSupportedValue,
        ):  # pragma: no cover
            return await super().serialize_value(request, value)

starlette_admin.contrib.sqla.fields.ImageField dataclass

Bases: ImageField

An ImageField that serializes values stored with sqlalchemy_file.ImageField.

Source code in starlette_admin/contrib/sqla/fields.py
@dataclass
class ImageField(BaseImageField):
    """An `ImageField` that serializes values stored with `sqlalchemy_file.ImageField`."""

    async def serialize_value(self, request: Request, value: Any) -> Any:
        try:
            return _serialize_sqlalchemy_file_library(
                request, value, request.state.action, self.multiple
            )
        except (
            ImportError,
            ModuleNotFoundError,
            NotSupportedValue,
        ):  # pragma: no cover
            return await super().serialize_value(request, value)

Converters

starlette_admin.contrib.sqla.converters.BaseSQLAModelConverter

Bases: BaseModelConverter

Source code in starlette_admin/contrib/sqla/converters.py
class BaseSQLAModelConverter(BaseModelConverter):
    def _external_converters(self) -> dict[Any, Callable[..., BaseField]]:
        return _EXTERNAL_CONVERTERS

    @classmethod
    def _extract_default(cls, column: ColumnElement) -> Any:
        """Return a Python-usable default value from a SQLAlchemy column.

        Only Python-side defaults (`Column.default`) on non-primary-key
        columns are extracted. Primary keys are typically auto-generated and
        are not pre-filled in create forms. Scalar defaults are returned
        as-is; callable defaults (e.g. ``datetime.now`` or ``uuid.uuid4``)
        are wrapped so they can be invoked without a SQLAlchemy execution
        context. SQL-expression defaults (``func.now()``) and server-side
        defaults are ignored because they cannot be meaningfully pre-filled
        in an HTML form.
        """
        column_name = getattr(column, "name", None)
        if isinstance(column, Label):
            _log.debug("_extract_default: skipping label column")
            return None
        if getattr(column, "primary_key", False):
            _log.debug(
                "_extract_default: skipping primary key column '%s'", column_name
            )
            return None
        if column.default is not None:
            if getattr(column.default, "is_scalar", False):
                default_value = column.default.arg
                _log.debug(
                    "_extract_default: scalar default for '%s' = %r",
                    column_name,
                    default_value,
                )
                return default_value
            if getattr(column.default, "is_callable", False):
                sa_arg = column.default.arg
                _log.debug(
                    "_extract_default: callable default for '%s' (%r)",
                    column_name,
                    sa_arg,
                )
                return lambda: sa_arg(None)
            _log.debug(
                "_extract_default: unsupported default for '%s' (%r)",
                column_name,
                column.default,
            )
        else:
            _log.debug("_extract_default: no default for '%s'", column_name)
        return None

    def get_converter(self, col_type: Any) -> Callable[..., BaseField]:
        converter = self.find_converter_for_col_type(type(col_type))
        if converter is not None:
            return converter
        raise NotSupportedColumn(  # pragma: no cover
            f"Column {col_type} can not be converted automatically. Find the appropriate field manually or provide "
            "your custom converter"
        )

    def convert(self, *args: Any, **kwargs: Any) -> BaseField:
        col_type = kwargs.get("type")
        field = self.get_converter(col_type)(*args, **kwargs)
        _log.debug(
            "Converted column %r (%s) → %s",
            kwargs.get("name"),
            type(col_type).__name__,
            type(field).__name__,
        )
        return field

    def find_converter_for_col_type(
        self,
        col_type: Any,
    ) -> Callable[..., BaseField] | None:
        types = inspect.getmro(col_type)

        # Search by module + name
        for col_type in types:
            type_string = f"{col_type.__module__}.{col_type.__name__}"
            if type_string in self.converters:
                return self.converters[type_string]

        # Search by name
        for col_type in types:
            if col_type.__name__ in self.converters:
                return self.converters[col_type.__name__]

            # Custom types built on TypeDecorator expose the underlying
            # implementation type via `impl`; fall back to converting that.
            if hasattr(col_type, "impl"):
                impl = (
                    col_type.impl
                    if callable(col_type.impl)
                    else col_type.impl.__class__
                )
                return self.find_converter_for_col_type(impl)
        return None  # pragma: no cover

    def convert_fields_list(
        self,
        *,
        fields: Sequence[Any],
        model: type[Any],
        explicit_fields: bool = False,
        **kwargs: Any,
    ) -> Sequence[BaseField]:
        mapper: Mapper = kwargs["mapper"]
        _log.debug(
            "convert_fields_list for %s (%d field(s))", model.__name__, len(fields)
        )
        converted_fields = []
        for field in fields:
            if isinstance(field, BaseField):
                converted_fields.append(field)
            else:
                if isinstance(field, InstrumentedAttribute):
                    attr = mapper.attrs.get(field.key)
                else:
                    attr = mapper.attrs.get(field)
                if attr is None:
                    _log.error(
                        "Cannot find column with key %r in model %s",
                        field,
                        model.__name__,
                    )
                    raise ValueError(f"Can't find column with key {field}")
                if isinstance(attr, RelationshipProperty):
                    key = slugify_class_name(attr.entity.class_.__name__)
                    _log.debug(
                        "Converting relationship %r (%s) for %s",
                        attr.key,
                        attr.direction.name,
                        model.__name__,
                    )
                    if attr.direction.name == "MANYTOONE" or (
                        attr.direction.name == "ONETOMANY" and not attr.uselist
                    ):
                        # The FK column(s) backing a MANYTOONE relation live on
                        # this model; mirror their nullability onto the
                        # relation field so it shows as required in the form.
                        # A reverse ONETOMANY (uselist=False) has its FK on the
                        # other model, so it can't be derived here.
                        required = attr.direction.name == "MANYTOONE" and all(
                            not local_col.nullable
                            for local_col, _ in attr.local_remote_pairs
                        )
                        converted_fields.append(
                            HasOne(attr.key, key=key, required=required)
                        )
                    else:
                        converted_fields.append(
                            HasMany(
                                attr.key,
                                key=key,
                                collection_class=attr.collection_class or list,
                            )
                        )
                elif isinstance(attr, ColumnProperty):
                    # A primary key column redeclared on a subclass in joined-table
                    # polymorphic inheritance still needs a field of its own.
                    is_inherited_pk = mapper.inherits is not None and any(
                        col.primary_key for col in attr.columns
                    )
                    if is_inherited_pk:
                        column = attr.columns[0]
                        converted_fields.append(
                            self.convert(
                                name=attr.key, type=column.type, column=column
                            ),
                        )
                    else:
                        assert len(attr.columns) == 1, (
                            "Multiple-column properties are not supported"
                        )
                        column = attr.columns[0]
                        if not column.foreign_keys or explicit_fields:
                            converted_field = self.convert(
                                name=attr.key, type=column.type, column=column
                            )
                            converted_fields.append(converted_field)
        _log.debug(
            "convert_fields_list for %s → %d converted field(s)",
            model.__name__,
            len(converted_fields),
        )
        return converted_fields

starlette_admin.contrib.sqla.converters.ModelConverter

Bases: BaseSQLAModelConverter

Source code in starlette_admin/contrib/sqla/converters.py
class ModelConverter(BaseSQLAModelConverter):
    @classmethod
    def _field_common(
        cls, *, name: str, column: ColumnElement, **kwargs: Any
    ) -> dict[str, Any]:
        if isinstance(column, Label):
            return {
                "name": column.key,
                "exclude_from_edit": True,
                "exclude_from_create": True,
            }
        return {
            "name": name,
            "help_text": column.comment,
            "default": cls._extract_default(column),
            "required": (
                not column.nullable
                and not isinstance(column.type, (Boolean,))
                and not column.default
                and not column.server_default
            ),
        }

    @classmethod
    def _string_common(cls, *, type: Any, **kwargs: Any) -> dict[str, Any]:
        if (
            isinstance(type, String)
            and isinstance(type.length, int)
            and type.length > 0
        ):
            return {"maxlength": type.length}
        return {}

    @classmethod
    def _file_common(cls, *, type: Any, **kwargs: Any) -> dict[str, Any]:
        return {"multiple": getattr(type, "multiple", False)}

    @converts(
        "String",
        "sqlalchemy.dialects.postgresql.base.MACADDR",
        "sqlalchemy.dialects.postgresql.types.MACADDR",
        "sqlalchemy_utils.types.locale.LocaleType",
    )  # includes Unicode
    def conv_string(self, *args: Any, **kwargs: Any) -> BaseField:
        return StringField(
            **self._field_common(*args, **kwargs),
            **self._string_common(*args, **kwargs),
        )

    @converts(
        "sqlalchemy.sql.sqltypes.Uuid",
        "sqlalchemy.dialects.postgresql.base.UUID",
        "sqlalchemy_utils.types.uuid.UUIDType",
    )
    def conv_uuid(self, *args: Any, **kwargs: Any) -> BaseField:
        return UUIDField(
            **self._field_common(*args, **kwargs),
            **self._string_common(*args, **kwargs),
        )

    @converts(
        "sqlalchemy.dialects.postgresql.base.INET",
        "sqlalchemy.dialects.postgresql.types.INET",
        "sqlalchemy_utils.types.ip_address.IPAddressType",
    )
    def conv_ip_address(self, *args: Any, **kwargs: Any) -> BaseField:
        return IPAddressField(
            ipv4=True,
            ipv6=True,
            **self._field_common(*args, **kwargs),
            **self._string_common(*args, **kwargs),
        )

    @converts("Text", "LargeBinary", "Binary")  # includes UnicodeText
    def conv_text(self, *args: Any, **kwargs: Any) -> BaseField:
        return TextAreaField(
            **self._field_common(*args, **kwargs),
            **self._string_common(*args, **kwargs),
        )

    @converts("Boolean", "BIT")
    def conv_boolean(self, *args: Any, **kwargs: Any) -> BaseField:
        return BooleanField(
            **self._field_common(*args, **kwargs),
        )

    @converts("DateTime")
    def conv_datetime(self, *args: Any, **kwargs: Any) -> BaseField:
        return DateTimeField(
            **self._field_common(*args, **kwargs),
        )

    @converts("Date")
    def conv_date(self, *args: Any, **kwargs: Any) -> BaseField:
        return DateField(
            **self._field_common(*args, **kwargs),
        )

    @converts("Time")
    def conv_time(self, *args: Any, **kwargs: Any) -> BaseField:
        return TimeField(
            **self._field_common(*args, **kwargs),
        )

    @converts("Enum")
    def conv_enum(self, *args: Any, **kwargs: Any) -> BaseField:
        _type = kwargs["type"]
        assert hasattr(_type, "enum_class")
        return EnumField(**self._field_common(*args, **kwargs), enum=_type.enum_class)

    @converts("Integer")  # includes BigInteger and SmallInteger
    def conv_integer(self, *args: Any, **kwargs: Any) -> BaseField:
        unsigned = getattr(kwargs["type"], "unsigned", False)
        extra = self._field_common(*args, **kwargs)
        if unsigned:
            extra["min"] = 0
        return IntegerField(**extra)

    @converts("Numeric")  # includes DECIMAL, Float/FLOAT, REAL, and DOUBLE
    def conv_numeric(self, *args: Any, **kwargs: Any) -> BaseField:
        if isinstance(kwargs["type"], Float) and not kwargs["type"].asdecimal:
            return FloatField(
                **self._field_common(*args, **kwargs),
            )
        return DecimalField(
            **self._field_common(*args, **kwargs),
        )

    @converts(
        "sqlalchemy.dialects.mysql.types.YEAR", "sqlalchemy.dialects.mysql.base.YEAR"
    )
    def conv_mysql_year(self, *args: Any, **kwargs: Any) -> BaseField:
        return IntegerField(**self._field_common(*args, **kwargs), min=1901, max=2155)

    @converts("ARRAY")
    def conv_array(self, *args: Any, **kwargs: Any) -> BaseField:
        _type = kwargs["type"]
        if isinstance(_type, ARRAY) and (
            _type.dimensions is None or _type.dimensions == 1
        ):
            kwargs.update(
                {
                    "column": Column(kwargs["name"], _type.item_type),
                    "type": _type.item_type,
                }
            )
            return ListField(self.convert(*args, **kwargs))
        raise NotSupportedColumn("Column ARRAY with dimensions != 1 is not supported")

    @converts(
        "JSON",
        "sqlalchemy_utils.types.json.JSONType",
        "sqlalchemy.dialects.postgresql.hstore.HSTORE",
    )
    def conv_json(self, *args: Any, **kwargs: Any) -> BaseField:
        return JSONField(**self._field_common(*args, **kwargs))

    @converts("sqlalchemy_file.types.FileField")
    def conv_sqla_filefield(self, *args: Any, **kwargs: Any) -> BaseField:
        return FileField(
            **self._field_common(*args, **kwargs), **self._file_common(*args, **kwargs)
        )

    @converts("sqlalchemy_file.types.ImageField")
    def conv_sqla_imagefield(self, *args: Any, **kwargs: Any) -> BaseField:
        return ImageField(
            **self._field_common(*args, **kwargs), **self._file_common(*args, **kwargs)
        )

    @converts("sqlalchemy_utils.types.arrow.ArrowType")
    def conv_arrow(self, *args: Any, **kwargs: Any) -> BaseField:
        return ArrowField(
            **self._field_common(*args, **kwargs),
        )

    @converts("sqlalchemy_utils.types.color.ColorType")
    def conv_color(self, *args: Any, **kwargs: Any) -> BaseField:
        return ColorField(
            **self._field_common(*args, **kwargs),
        )

    @converts("sqlalchemy_utils.types.email.EmailType")
    def conv_email(self, *args: Any, **kwargs: Any) -> BaseField:
        return EmailField(
            **self._field_common(*args, **kwargs),
            **self._string_common(*args, **kwargs),
        )

    @converts("sqlalchemy_utils.types.password.PasswordType")
    def conv_password(self, *args: Any, **kwargs: Any) -> BaseField:
        return PasswordField(
            **self._field_common(*args, **kwargs),
            **self._string_common(*args, **kwargs),
        )

    @converts("sqlalchemy_utils.types.phone_number.PhoneNumberType")
    def conv_phonenumbers(self, *args: Any, **kwargs: Any) -> BaseField:
        return PhoneField(
            **self._field_common(*args, **kwargs),
            **self._string_common(*args, **kwargs),
        )

    @converts("sqlalchemy_utils.types.scalar_list.ScalarListType")
    def conv_scalar_list(self, *args: Any, **kwargs: Any) -> BaseField:
        return ListField(
            StringField(
                **self._field_common(*args, **kwargs),
            )
        )

    @converts("sqlalchemy_utils.types.url.URLType")
    def conv_url(self, *args: Any, **kwargs: Any) -> BaseField:
        return URLField(
            **self._field_common(*args, **kwargs),
        )

    @converts("sqlalchemy_utils.types.timezone.TimezoneType")
    def conv_timezone(self, *args: Any, **kwargs: Any) -> BaseField:
        return TimeZoneField(
            **self._field_common(*args, **kwargs),
            coerce=kwargs["type"].python_type,
        )

    @converts("sqlalchemy_utils.types.country.CountryType")
    def conv_country(self, *args: Any, **kwargs: Any) -> BaseField:
        return CountryField(
            **self._field_common(*args, **kwargs),
        )

    @converts("sqlalchemy_utils.types.currency.CurrencyType")
    def conv_currency(self, *args: Any, **kwargs: Any) -> BaseField:
        return CurrencyField(
            **self._field_common(*args, **kwargs),
        )

    @converts("sqlalchemy_utils.types.choice.ChoiceType")
    def conv_choice(self, *args: Any, **kwargs: Any) -> BaseField:
        _type = kwargs["type"]
        choices = _type.choices
        if isinstance(choices, type) and issubclass(choices, enum.Enum):
            return EnumField(
                **self._field_common(*args, **kwargs),
                enum=choices,
                coerce=_type.python_type,
            )
        return EnumField(
            **self._field_common(*args, **kwargs),
            choices=choices,
            coerce=_type.python_type,
        )

    @converts("sqlalchemy_utils.types.pg_composite.CompositeType")
    def conv_composite_type(self, *args: Any, **kwargs: Any) -> BaseField:
        _type = kwargs["type"]
        fields = []
        field_common = self._field_common(*args, **kwargs)
        for col in _type.columns:
            kwargs.update({"name": col.name, "column": col, "type": col.type})
            fields.append(self.convert(*args, **kwargs))
        return CollectionField(
            field_common["name"], fields=fields, required=field_common["required"]
        )

Exceptions

starlette_admin.contrib.sqla.exceptions.InvalidModelError

Bases: StarletteAdminException

Source code in starlette_admin/contrib/sqla/exceptions.py
class InvalidModelError(StarletteAdminException):
    pass

starlette_admin.contrib.sqla.exceptions.InvalidQuery

Bases: StarletteAdminException

Source code in starlette_admin/contrib/sqla/exceptions.py
class InvalidQuery(StarletteAdminException):
    pass

starlette_admin.contrib.sqla.exceptions.NotSupportedColumn

Bases: StarletteAdminException

Source code in starlette_admin/contrib/sqla/exceptions.py
class NotSupportedColumn(StarletteAdminException):
    pass

starlette_admin.contrib.sqla.exceptions.NotSupportedValue

Bases: StarletteAdminException

Source code in starlette_admin/contrib/sqla/exceptions.py
class NotSupportedValue(StarletteAdminException):
    pass

Note

Concrete filter classes (EqualFilter, ContainsFilter, BetweenFilter, and so on) are not enumerated here. They mirror the backend-agnostic filters documented in Filters one-to-one; the SQLAlchemy-specific behavior worth knowing is covered in SQLAlchemy.