Created
October 23, 2013 12:35
-
-
Save mssola/7117835 to your computer and use it in GitHub Desktop.
Map model names into database tables by using metaprogramming in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Persistent(type): | |
def __new__(self, name, bases, dct): | |
self.tables = dict() | |
return super(Persistent, self).__new__(self, name, bases, dct) | |
def __init__(self, name, bases, dct): | |
table = name.lower() + 's' | |
self.tables[self] = table | |
super(Persistent, self).__init__(name, bases, dct) | |
class Model(object, metaclass = Persistent): | |
def table_name(self): | |
return Persistent.tables[self.__class__] | |
class User(Model): | |
pass | |
u = User() | |
print(u.table_name()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment