Replies: 1 comment 1 reply
-
Starlette Admin provides support for Composite Types in SQLAlchemy (example here ), Embedded Documents in MongoEngine (example here), and Embedded Models in Odmantic (example here). Currently, Starlette Admin does not have built-in support for InlineModel. Full example: from typing import Any, Dict
import uvicorn
from sqlalchemy import ForeignKey, create_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
from starlette.applications import Starlette
from starlette.requests import Request
from starlette_admin import CollectionField, IntegerField, StringField
from starlette_admin.contrib.sqla import Admin, ModelView
class Base(DeclarativeBase):
pass
engine = create_engine("sqlite:///test.db", connect_args={"check_same_thread": False})
# Define your model
class Status(Base):
__tablename__ = "status"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
class Company(Base):
__tablename__ = "company"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
status_id: Mapped[int] = mapped_column(ForeignKey("status.id"))
status: Mapped["Status"] = relationship(cascade="all")
class CompanyView(ModelView):
fields = [
"id",
"name",
CollectionField(
"status",
fields=[
IntegerField("id", read_only=True),
StringField("name"),
],
),
]
async def create(self, request: Request, data: Dict[str, Any]) -> Any:
data["status"] = Status(name=data["status"]["name"])
return await super().create(request, data)
async def edit(self, request: Request, pk: Any, data: Dict[str, Any]) -> Any:
status: Status = request.state.session.get(Status, data["status"]["id"])
status.name = data["status"]["name"]
data["status"] = status
return await super().edit(request, pk, data)
Base.metadata.create_all(engine)
app = Starlette() # FastAPI()
# Create admin
admin = Admin(engine, title="Example: SQLAlchemy")
# Add view
admin.add_view(CompanyView(Company))
# Mount admin to your app
admin.mount_to(app)
if __name__ == "__main__":
uvicorn.run(app) |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
HI. Does Starlette Admin support displaying grandchilren of a particular model?
For example, if I have two modes:
Company:
Status:
Is there a way to show the account name in the company's admin panel?
I imagine the syntax would be
class Company(ModelView):
fields = ["id", "status.id", "status.name"]
I am also very interested in whether you can filter by the grandchild field too.
Beta Was this translation helpful? Give feedback.
All reactions