Pegase745 / sqlalchemy-datatables

SQLAlchemy integration of jQuery DataTables >= 1.10.x (Pyramid and Flask examples)
MIT License
159 stars 67 forks source link

Get a child element as table column #100

Closed SteekDev closed 7 years ago

SteekDev commented 7 years ago

Model:

class Parent(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    child = db.relationship('Key', backref='parent')

class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))
    price = db.Column(db.Integer)
columns = [
    ColumnDT(Parent.id, mData='1'),
    ColumnDT(func.count(Parent.child), mData='2', global_search=False), # it's works
    ColumnDT(Parent.child[0].id, mData='3'), # get id 1st child, does not work
    ColumnDT(Parent.child[1].id, mData='4'), # get id 2nd child, does not work

]

query = db.session.query().select_from(Parent).join(Child).group_by(Parent.id)

Example: Parent_1.id - Parent_1.countChild - Parent_1.Child_1.id - Parent_1.Child_2.id Parent_2.id - Parent_2.countChild - Parent_2.Child_1.id - Parent_2.Child_2.id Parent_3.id - Parent_3.countChild - Parent_3.Child_1.id - Parent_3.Child_2.id

tdamsma commented 7 years ago

The queries you are righting are evaluated as sql code, not as python objects. Therefore you can't use the python backrefs to make one-to-many links. The way to deal with this is to construct a query with sqlalchemy that returns what you want, and then pass that query to that datatable. I think you should be able to do this with joining a subquery where you filter for rank = 1 and rank =2, but this quickly gets ugly. See here: https://github.com/Pegase745/sqlalchemy-datatables/issues/83