Created
March 26, 2018 23:04
-
-
Save marianoeramirez/19aee2d6fa9187d003ad2d8b64e692ba to your computer and use it in GitHub Desktop.
Dynamyc model
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
def add_field(sender, object): | |
table_name = sender._meta.db_table | |
app = sender._meta.app_label | |
model = sender.__name__.lower() | |
if object.system: | |
field = get_model_field(sender, object) | |
if field is not None: | |
field.verbose_name = object.label | |
if field.null: | |
field.blank = not object.required | |
return None | |
if object.typefield.nonfield: | |
return None | |
if not search_field(sender, object.name): | |
field = get_field(object) | |
field.contribute_to_class(sender, object.name) | |
field2 = copy.deepcopy(field) | |
db_column_names = [row[0] for row in | |
connection.introspection.get_table_description(connection.cursor(), table_name)] | |
if field.column not in db_column_names: | |
db.start_transaction() | |
db.add_column(table_name, field.column, field) | |
db.execute_deferred_sql() | |
db.commit_transaction() |
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
from django.db.models.signals import class_prepared | |
from livesettings.functions import ConfigurationSettings | |
import config | |
def add_field(sender, **kwargs): | |
""" | |
class_prepared signal handler that checks for the model named | |
MyModel as the sender, and adds a new Field to it | |
to it. | |
""" | |
if sys is None or ( | |
'schemamigration' not in sys.argv and 'migrate' not in sys.argv and 'syncdb' not in sys.argv): # and 'test' not in sys.argv | |
if hasattr(sender, 'dynamic'): | |
# if sender.__name__ == 'Site': | |
for p in FieldModel.objects.all().filter(model=sender.__name__, deleted=False, system=False, | |
preexists=None): | |
dynamically.add_field(sender, p) | |
mgr = ConfigurationSettings() | |
mgr.get_config("rnd", "RESTART_SERVER_FIELD").update(False) | |
connection.close() | |
class_prepared.connect(add_field) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment