I am trying to figure out the correct join query setup within SQLAlchemy, but I can't seem to get my head around it.
I have the following table setup (simplified, I left out the non-essential fields):
class Group(db.Model):
id = db.Column(db.Integer, primary_key = True)
number = db.Column(db.SmallInteger, index = True, unique = True)
member = db.relationship('Member', backref = 'groups', lazy = 'dynamic')
class Member(db.Model):
id = db.Column(db.Integer, primary_key = True)
number = db.Column(db.SmallInteger, index = True)
groupid = db.Column(db.Integer, db.ForeignKey('group.id'))
item = db.relationship('Item', backref = 'members', lazy = 'dynamic')
class Version(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(80), index = True)
items = db.relationship('Item', backref='versions', lazy='dynamic')
class Item(db.Model):
id = db.Column(db.Integer, primary_key = True)
member = db.Column(db.Integer, db.ForeignKey('member.id'))
version = db.Column(db.Integer, db.ForeignKey('version.id'))
So the relationships are the following:
- 1:n Group Member
- 1:n Member Item
- 1:n Version Item
I would like to construct a query by selecting all Item-Rows from the database, that have a certain version. Then I would like to order them by Group and then by Member. The output using Flask/WTForm should look something like this:
* GroupA
* MemberA
* ItemA (version = selected by user)
* ItemB ( dito )
* Member B
* ItemC ( dito )
....
I have come up with something like the following query, but I am pretty sure that it is not correct (and inefficient)
session.query(Item,Member,Group,Version)
.join(Member).filter(version.id==1)
.order_by(Group).order_by(Member).all()
My first intuitive approach would have been to create something like
Item.query.join(Member, Item.member==Member.id)
.filter(Member.versions.name=='MySelection')
.order_by(Member.number).order_by(Group.number)
but obviously, this doesn't work at all. The join operation on the Version table does not seem to produce the type of join between the two tables that I expected. Maybe I am totally misunderstanding the concept, but after reading the tutorials this would have made sense to me.
Following will give you the objects you need in one query:
However, the result you get will be a list of tuples
(Group, Member, Item, Version)
. Now it is up to you to display it in a tree form. Code below might prove useful though:Update-1: If you are willing to forgo
lazy = 'dynamic'
for the first two relationships, you can a query to load a wholeobject network
(as opposed to tuples above) with the code: