pallets-eco / flask-admin

Simple and extensible administrative interface framework for Flask
https://flask-admin.readthedocs.io
BSD 3-Clause "New" or "Revised" License
5.75k stars 1.57k forks source link

Dotted Path for Related Column on Edit Form #1852

Open cancan101 opened 5 years ago

cancan101 commented 5 years ago

Is there an equivalent to the dotted path syntax for related fields on column_list for the edit form:

When using SQLAlchemy models, you can reference related columns like this::
class MyModelView(BaseModelView):
column_list = (‘<relationship>.<related column name>’,)

i.e. where fields can be set / read from a column on a relationship?

This issue: https://github.com/flask-admin/flask-admin/issues/1479 is related.

ljluestc commented 2 months ago

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin, BaseView, expose
from flask_admin.contrib.sqla import ModelView
from sqlalchemy.orm import relationship

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///your_database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# Example SQLAlchemy models with relationships
class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)

    # One-to-Many relationship with Book
    books = relationship('Book', backref='author', lazy=True)

class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    author_id = db.Column(db.Integer, db.ForeignKey('author.id'), nullable=False)

# Customized ModelView to handle related columns
class BookModelView(ModelView):
    column_list = ('title', 'author.name')  # Access author's name through the relationship

# Flask-Admin setup
admin = Admin(app, name='Admin Panel', template_mode='bootstrap3')
admin.add_view(BookModelView(Book, db.session))

if __name__ == '__main__':
    app.run(debug=True)