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.69k stars 1.56k forks source link

Tags and M2M #1499

Open VoittajaTomi opened 7 years ago

VoittajaTomi commented 7 years ago

Hello, I am trying to implement tags in my app. I found a guide to solve similar problem: https://gist.github.com/riteshreddyr/73404faf44dafa2be2f0

The problem is though, that this solution does not seem to work with current flask_admin version, because the sqla.ModelView -class does not have _search_joins property.

Is there any workaround? What I am trying to do is that a certain model should have a variable amount of "tags" to describe its properties.

ljluestc commented 3 days ago

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.associationproxy import association_proxy

db = SQLAlchemy()

# Tag model for defining tags
class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True)

# Association table to link items and tags
item_tags = db.Table('item_tags',
    db.Column('item_id', db.Integer, db.ForeignKey('item.id')),
    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))
)

# Item model with tags association
class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    tags = db.relationship('Tag', secondary=item_tags, backref=db.backref('items', lazy='dynamic'))

    # Proxy property to access tag names directly
    tag_names = association_proxy('tags', 'name')