Skip to content

Instantly share code, notes, and snippets.

@ra0x3
Created March 4, 2020 05:01
Show Gist options
  • Save ra0x3/6b45a8384d756fdc5bc789896be59eee to your computer and use it in GitHub Desktop.
Save ra0x3/6b45a8384d756fdc5bc789896be59eee to your computer and use it in GitHub Desktop.
Helper classes to allow recursive automatic joins in peewee
class Direct:
def __init__(self, native_key, foreign_key):
"""
Represents a direct relationship from one 'native'
model, to one 'foreign' model
"""
self.native_key = native_key
self.foreign_key = foreign_key
class Through:
def __init__(self, native_key, thru_model, thru_key, foreign_key):
"""
Represents a many-to-many relationship from one 'native' model
through a 'thru' model, to one 'foreign' mdel
"""
self.native_key = native_key
self.thru_model = thru_model
self.thru_key = thru_key
self.foreign_key = foreign_key
class Relationship:
def __init__(self, how, relation):
"""
Representing either a 'Direct' or 'Through'
relationship for a 'native' model and a 'foreign' model
"""
self.how = how
self.relation = relation
class ModelRelationship:
def __init__(self, data):
"""
A container for many 'Direct' and 'Through'
relationships on a given model
"""
self.data = data
def has_thru(self, tablename):
""" Whether a model has a through table or not """
rel = self.data.get(tablename) == "through"
return rel.how == "through" if rel else False
def thru_for(self, tablename):
""" Return a through model for a given native model """
return self.data[tablename].relation.thru_model
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment