aminalaee / sqladmin

SQLAlchemy Admin for FastAPI and Starlette
https://aminalaee.dev/sqladmin/
BSD 3-Clause "New" or "Revised" License
1.81k stars 182 forks source link

deferred=True which will lead to DetachedInstanceError #815

Open vahidzhe opened 1 week ago

vahidzhe commented 1 week ago

Checklist

Describe the bug

created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(tz=pytz.timezone('Asia/Baku')),
        deferred=True,
    )
updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        server_default=func.now(tz=pytz.timezone('Asia/Baku')),
        onupdate=func.now(tz=pytz.timezone('Asia/Baku')),
        deferred=True,
    )

In my code, when deferred=True in the created_at field, it is not possible to edit an instance of my model in the Admin panel.

raise orm_exc.DetachedInstanceError(
  sqlalchemy.orm.exc.DetachedInstanceError: Parent instance <User at 0x7f215df6ce10> is not bound to a Session; 
  deferred load operation of attribute 'created_at' cannot proceed (Background on this error at: https://sqlalche.me/e/20/bhk3)

https://docs.sqlalchemy.org/en/20/errors.html#error-bhk3

Steps to reproduce the bug

No response

Expected behavior

No response

Actual behavior

No response

Debugging material

No response

Environment

Windows 10 / ptyhon 3.11 / sqladmin 0.19

Additional context

No response

aminalaee commented 1 week ago

Hi, Just a question, what is your expected behaviour here? I'm guessing you don't want to be able edit created_at and updated_at right?

In that case you can just specify form_columns and leave out columns like created_at to not be shown.

class MyAdmin(...):
    form_columns = ["column_a"]
vahidzhe commented 1 week ago

I used form_excluded_columns and it worked. Thanks

vahidzhe commented 1 week ago

@aminalaee But there may be places where it is necessary to edit the created_at field, so what can I do?