跳转至
受监督的机器翻译

本文内容由机器翻译生成,并遵循人工维护的术语表与风格指南。由于译文未经逐行人工审校,可能偶有错误或表达不当之处。

如有任何出入,请以英文原版为准,英文原版是权威来源。

阅读英文原版

Contrib:SQLModel

SQLModel 后端(starlette_admin.contrib.sqlmodel)的完整属性和方法参考,由 docstring 生成。SQLModel 底层基于 SQLAlchemy,因此 AdminModelViewSQLAlchemy 后端的轻量子类,并通过模型的 Pydantic 层校验表单数据。如需面向任务的指引,请参阅 SQLModel 集成

starlette_admin.contrib.sqlmodel.admin.Admin

Bases: Admin

Source code in starlette_admin/contrib/sqlmodel/admin.py
class Admin(BaseAdmin):
    pass

starlette_admin.contrib.sqlmodel.view.ModelView

Bases: ModelView

Source code in starlette_admin/contrib/sqlmodel/view.py
class ModelView(BaseModelView):
    def __init__(
        self,
        model: type[SQLModel],
        icon: str | None = None,
        display_name: str | None = None,
        menu_label: str | None = None,
        key: str | None = None,
        converter: BaseSQLAModelConverter | None = None,
    ):
        super().__init__(model, icon, display_name, menu_label, key, converter)

    async def validate(self, request: Request, data: dict[str, Any]) -> None:
        """Validate form data against the SQLModel, excluding file and relation fields.

        File and relation fields hold values (uploads, related objects) that the
        Pydantic model itself cannot validate, so they are stripped from `data`
        before calling `model_validate`.
        """
        fields = self.get_fields_list(request)
        fields_to_exclude = [
            f.name for f in fields if isinstance(f, (FileField, RelationField))
        ]
        payload = {k: v for k, v in data.items() if k not in fields_to_exclude}
        payload.update(_fk_values_from_relations(self.model, fields, data))
        self.model.model_validate(payload)

    async def handle_exception(self, request: Request, exc: Exception) -> None:
        if isinstance(exc, ValidationError):
            key_map = _fk_columns_by_relation(self.model, self.get_fields_list(request))
            raise pydantic_error_to_form_validation_errors(exc, key_map)
        return await super().handle_exception(request, exc)  # pragma: no cover

validate(request, data) async

Validate form data against the SQLModel, excluding file and relation fields.

File and relation fields hold values (uploads, related objects) that the Pydantic model itself cannot validate, so they are stripped from data before calling model_validate.

Source code in starlette_admin/contrib/sqlmodel/view.py
async def validate(self, request: Request, data: dict[str, Any]) -> None:
    """Validate form data against the SQLModel, excluding file and relation fields.

    File and relation fields hold values (uploads, related objects) that the
    Pydantic model itself cannot validate, so they are stripped from `data`
    before calling `model_validate`.
    """
    fields = self.get_fields_list(request)
    fields_to_exclude = [
        f.name for f in fields if isinstance(f, (FileField, RelationField))
    ]
    payload = {k: v for k, v in data.items() if k not in fields_to_exclude}
    payload.update(_fk_values_from_relations(self.model, fields, data))
    self.model.model_validate(payload)

starlette_admin.contrib.sqlmodel.view.InlineModelView

Bases: InlineModelView

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

Inherits FK detection and session logic from the SQLAlchemy InlineModelView and adds SQLModel Pydantic validation on top.

Declare model as a class attribute (a SQLModel table class). fk_attr is optional and is auto-detected from the parent's SQLAlchemy relationship when omitted.

Example:

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


class PostView(ModelView):
    inlines = [CommentInline]
```
Source code in starlette_admin/contrib/sqlmodel/view.py
class InlineModelView(SQLAInlineModelView):
    """Inline editing of SQLModel-backed related records inside a parent form.

    Inherits FK detection and session logic from the SQLAlchemy
    `InlineModelView` and adds SQLModel Pydantic validation on top.

    Declare `model` as a class attribute (a `SQLModel` table class). `fk_attr`
    is optional and is auto-detected from the parent's SQLAlchemy relationship
    when omitted.

    Example:

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


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

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

    async def validate(self, request: Request, data: dict[str, Any]) -> None:
        fields = self.get_fields_list(request)
        fields_to_exclude = [
            f.name for f in fields if isinstance(f, (FileField, RelationField))
        ]
        payload = {k: v for k, v in data.items() if k not in fields_to_exclude}
        payload.update(_fk_values_from_relations(self.model, fields, data))
        self.model.model_validate(payload)

    async def handle_exception(self, request: Request, exc: Exception) -> None:
        if isinstance(exc, ValidationError):
            key_map = _fk_columns_by_relation(self.model, self.get_fields_list(request))
            raise pydantic_error_to_form_validation_errors(exc, key_map)
        return await super().handle_exception(request, exc)  # pragma: no cover