Skip to content

Field(allow_mutation=False) doesn't have same behavior as pydantic #262

Open
@winglian

Description

@winglian

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

import pytest
import sqlmodel
import pydantic


class MyPydanticModel(pydantic.BaseModel):
    id: str
    data: str = pydantic.Field(allow_mutation=False)

    class Config:
        validate_assignment = True


class MySqlmodelModel(sqlmodel.SQLModel):
    id: str
    data: str = sqlmodel.Field(allow_mutation=False)

    class Config:
        validate_assignment = True


class TestSuite:
    def test_pydantic_can_create(self):
        MyPydanticModel(id='abc', data="foo")

    def test_pydantic_raises_on_update(self):
        my_pyd_mdl = MyPydanticModel(id='abc', data="foo")
        with pytest.raises(TypeError):
            my_pyd_mdl.data = "bar"

    def test_sqlmodel_can_create(self):
        MySqlmodelModel(id='abc', data="foo")

    def test_sqlmodel_raises_on_update(self):
        my_sqlmdl_mdl = MySqlmodelModel(id='abc', data="foo")
        with pytest.raises(TypeError):
            my_sqlmdl_mdl.data = "bar"

Description

When setting a Field(allow_mutation=False) in combination with the required validate_assignment = True configuration on a SQLModel, the framework doesn't even allow the field to be set in the initial construction of the model. This is allowed in pydantic. I've attached a test suite that we should expect to pass, but it fails both the SQLModel specific tests.

Operating System

macOS

Operating System Details

Big Sur 11.3.1

SQLModel Version

0.0.6

Python Version

3.9.9

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions