Skip to content

Instantly share code, notes, and snippets.

@Quidge
Created April 6, 2018 22:45
Show Gist options
  • Save Quidge/3d56356ab1bc57d70b4cea132e5e0d46 to your computer and use it in GitHub Desktop.
Save Quidge/3d56356ab1bc57d70b4cea132e5e0d46 to your computer and use it in GitHub Desktop.
# These are my models (some attributes removed for clarity)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
# user many-to-many size associations (using link tables)
sz_shirt_dress_sleeve = db.relationship(
'SizeKeyShirtDressSleeve', secondary=LinkUserSizeShirtDressSleeve, backref=db.backref('users', lazy='dynamic'))
LinkUserSizeShirtDressSleeve = db.Table(
'link_user_size_shirt_dress_sleeve',
db.Column('size_id', db.Integer, db.ForeignKey('size_key_shirt_dress_sleeve.id'), primary_key=True),
db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True)
)
class SizeKeyShirtDressSleeve(db.Model):
id = db.Column(db.Integer, primary_key=True)
size = db.Column(db.Numeric(4,2))
def __repr__(self):
'''
I'm writing a view that will generate a page to list all of a User's sizes, AS WELL as all possible sizes (a user can be associated with multiple sizes). Possible sleeve sizes range from 30.0 to 38.0 and incrementing by 0.5.
For example, say User with ID 1 is associated with sizes 30.0, 30.5, 31.0, and 32.0. I need a query for that user that returns this:
Size | UserIsAssociated
--------|-------------------
30.0 | True
30.5 | True
31.0 | True
31.5 | False
32.0 | True
32.5 | False
33.0 | False
...
38.0 | False
I'm certain this must be possible, because I can do it in raw SQL. The SQL query that generates such a table looks like:
SELECT
size,
case WHEN link_user_size_shirt_dress_sleeve.size_id IS NOT NULL
THEN 'true' ELSE 'false' END AS present
FROM size_key_shirt_dress_sleeve
LEFT JOIN link_user_size_shirt_dress_sleeve
ON size_key_shirt_dress_sleeve.id = link_user_size_shirt_dress_sleeve.size_id
;
This should (I think) be a combination of outerjoin() and case(), but I've been having significant difficulty.
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment