Skip to content

Conversation

iYasha
Copy link

@iYasha iYasha commented May 3, 2025

The problem

SqlalchemyCrud.on_update_pre uses model_fields function for both PyDantic.BaseModel and SQLAlchemy.Base, but the last has no attribute model_fields

Steps to reproduce

class CountryInDBSchema(BaseModel):
    id: UUID
    name: str
    deleted_at: Optional[datetime] = None

    class Config:
        orm_mode = True


class Country(Base):
    __tablename__ = "countries"
    __pydantic_model__ = CountryInDBSchema
    
    id = sa.Column(UUID, primary_key=True, index=True)
    name = sa.Column(sa.String, nullable=False)
    deleted_at = sa.Column(sa.DateTime(timezone=False), nullable=True, index=True)
  1. Insert a new record to the countries table with deleted_at=null
  2. Try to update this record in amis admin panel
  3. Get error
  File "fastapi_amis_admin/crud/_sqlalchemy.py", line 575, in route
    values = await self.on_update_pre(request, data, item_id=item_id)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "fastapi_amis_admin/crud/_sqlalchemy.py", line 463, in on_update_pre
    data = {key: val for key, val in data.items() if val is not None or field_allow_none(model_fields(self.model)[key])}
                                                                                         ^^^^^^^^^^^^^^^^^^^^^^^^
  File "fastapi_amis_admin/utils/pydantic.py", line 86, in model_fields
    for field_name, field in model.model_fields.items():
                             ^^^^^^^^^^^^^^^^^^
AttributeError: type object 'Country' has no attribute 'model_fields'

How to fix

To fix this issue, we should check if self.model is SQLAlchemy model If so, then we should use __pydantic_model__ for model_fields, otherwise just pass self.model

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant