aminalaee / sqladmin

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

Use sqladmin with sqlalchemy core #831

Open sheldygg opened 2 days ago

sheldygg commented 2 days ago

Checklist

Is your feature related to a problem? Please describe.

I want use sqladmin with sqlalchemy core

Describe the solution you would like.

Looks like we must rewrite many code

Describe alternatives you considered

No response

Additional context

No response

aminalaee commented 4 hours ago

Please provide a minimal example with the error of what is happening

sheldygg commented 4 hours ago
from sqlalchemy import Column, Integer, String, create_engine, Table, MetaData
from fastapi import FastAPI
from sqladmin import Admin, ModelView

engine = create_engine(
    "sqlite:///example.db",
    connect_args={"check_same_thread": False},
)

metadata = MetaData()

User = Table(
    "users",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("name", String),
)
metadata.create_all(engine)

class UserAdmin(ModelView, model=User):
    column_list = [User.columns.id, User.columns.name]

app = FastAPI()
admin = Admin(app, engine)

admin.add_view(UserAdmin)
  File "/Users/sheldy/projects/test-sqladmin/test.py", line 20, in <module>
    class UserAdmin(ModelView, model=User):
  File "/Users/sheldy/projects/test-sqladmin/venv/lib/python3.11/site-packages/sqladmin/models.py", line 83, in __new__
    if not model:
  File "/Users/sheldy/projects/test-sqladmin/venv/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 748, in __bool__
    raise TypeError("Boolean value of this clause is not defined")
TypeError: Boolean value of this clause is not defined

I read sqladmin sources and realized that your code is addicted to orm

sheldygg commented 4 hours ago

If I change if not model condition to if model is None I will receive the following error

  File "/Users/sheldy/projects/test-sqladmin/test.py", line 20, in <module>
    class UserAdmin(ModelView, model=User):
  File "/Users/sheldy/projects/test-sqladmin/venv/lib/python3.11/site-packages/sqladmin/models.py", line 93, in __new__
    cls.pk_columns = get_primary_keys(model)
                     ^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/sheldy/projects/test-sqladmin/venv/lib/python3.11/site-packages/sqladmin/helpers.py", line 176, in get_primary_keys
    return tuple(inspect(model).mapper.primary_key)
                 ^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Table' object has no attribute 'mapper'