def install_model(custom_model): from django.db import connection from django.db.backends.base.schema import BaseDatabaseSchemaEditor editor = BaseDatabaseSchemaEditor(connect) try: editor.create_model(model=custom_model) except AttributeError as aerror: print(aerror)
def desde_tabla(self, instancia): opciones = {"__module__": "capas"} geom = instancia.atributos.filter(nombre="geom").first() if geom is None: raise ValidationError({"capa": "falta atributo geom"}) opciones.update({"geom": self.get_tipo(geom.tipo)}) for i in instancia.atributos.all(): if i.nombre.lower() in ["id", "geom"]: continue opciones.update({i.nombre.lower(): self.get_tipo(i.tipo)}) modelo = type(instancia.nombre, (models.Model, ), opciones) esquema = BaseDatabaseSchemaEditor(connection) esquema.deferred_sql = [] esquema.create_model(modelo)
def importar_tabla(self): """ crea la tabla con su estructura en la base de datos """ self.validar_capa() attrs = self.capa.common_attributes opciones = {"__module__": "capas"} for i in attrs: if i.lower() == "id": continue opciones.update( {i.lower(): models.CharField(max_length=255, null=True)}) opciones.update({"geom": self.get_tipo(self.capa[0].geometry.type)}) modelo = type(self.nombre, (models.Model, ), opciones) esquema = BaseDatabaseSchemaEditor(connection) esquema.deferred_sql = [] esquema.create_model(modelo) self.alterar_registros_nuevo(modelo) self.registrar_estructura(attrs)
def __init__(self): self.TimeSeriesBaseModel = get_model(self.app_label, self.model_name) # first check to see if the model exists in Django's model cache from django.apps import registry try: if registry.apps.get_model(self.app_label, self.name): self.TimeSeriesModel = registry.apps.get_model( self.app_label, self.name) return except LookupError: pass # model did not exist in Django's model cache, so let's build it and load it class Meta: db_table = self.name # TODO support overriding table name fields = { 'original_model': models.ForeignKey(self.TimeSeriesBaseModel), 'timestamp': models.DateTimeField(db_index=True), '__module__': self.app_label + '.models', 'Meta': Meta } for f in self.time_series_properties: if f == 'timestamp': raise Exception('Cannot time series a field named "timestamp"') field_class = None max_digits = 0 decimal_places = 0 max_length = 0 for model_field in self.TimeSeriesBaseModel._meta.fields: if model_field.name == f: field_class = model_field.__class__ # TODO support all default django fields if not (issubclass(field_class, models.DecimalField) or issubclass(field_class, models.IntegerField) or issubclass(field_class, models.CharField) or issubclass(field_class, models.TextField) or issubclass(field_class, models.URLField) or issubclass(field_class, models.DateTimeField) or issubclass(field_class, models.DateField) or issubclass(field_class, models.FloatField)): raise Exception("Class {} not supported".format( field_class.__name__)) if field_class == models.DecimalField: # must bring over params in the case of decimal field max_digits = model_field.max_digits decimal_places = model_field.decimal_places if field_class == models.CharField: # must bring over max length in case of char field max_length = model_field.max_length break if field_class is None: raise Exception( "Field {} could not be found in class {}".format( f, self.TimeSeriesBaseModel.__name__)) fields[f] = field_class() if field_class == models.DecimalField: fields[f].max_digits = max_digits fields[f].decimal_places = decimal_places if field_class == models.CharField: fields[f].max_length = max_length for field_name, field_instance, function in self.time_series_functions: fields[field_name] = field_instance self.TimeSeriesModel = type(self.name, (models.Model, ), fields) # next make sure that the tables exist in the database. if not, build them. from django.db import connection try: cursor = connection.cursor() cursor.execute("SELECT * FROM {} LIMIT 1".format(self.name)) except ProgrammingError: # Looks like the table doesn't exist! Let's build it! from django.db import connection from django.db.backends.base.schema import BaseDatabaseSchemaEditor schema_editor = BaseDatabaseSchemaEditor(connection) with schema_editor: schema_editor.create_model(self.TimeSeriesModel)
def __init__(self): self.TimeSeriesBaseModel = get_model(self.app_label, self.model_name) # first check to see if the model exists in Django's model cache from django.apps import registry try: if registry.apps.get_model(self.app_label, self.name): self.TimeSeriesModel = registry.apps.get_model(self.app_label, self.name) return except LookupError: pass # model did not exist in Django's model cache, so let's build it and load it class Meta: db_table = self.name # TODO support overriding table name fields = { 'original_model': models.ForeignKey(self.TimeSeriesBaseModel), 'timestamp': models.DateTimeField(db_index=True), '__module__': self.app_label + '.models', 'Meta': Meta } for f in self.time_series_properties: if f == 'timestamp': raise Exception('Cannot time series a field named "timestamp"') field_class = None max_digits = 0 decimal_places = 0 max_length = 0 for model_field in self.TimeSeriesBaseModel._meta.fields: if model_field.name == f: field_class = model_field.__class__ # TODO support all default django fields if not (issubclass(field_class, models.DecimalField) or issubclass(field_class, models.IntegerField) or issubclass(field_class, models.CharField) or issubclass(field_class, models.TextField) or issubclass(field_class, models.URLField) or issubclass(field_class, models.DateTimeField) or issubclass(field_class, models.DateField) or issubclass(field_class, models.FloatField)): raise Exception("Class {} not supported".format(field_class.__name__)) if field_class == models.DecimalField: # must bring over params in the case of decimal field max_digits = model_field.max_digits decimal_places = model_field.decimal_places if field_class == models.CharField: # must bring over max length in case of char field max_length = model_field.max_length break if field_class is None: raise Exception("Field {} could not be found in class {}".format(f, self.TimeSeriesBaseModel.__name__)) fields[f] = field_class() if field_class == models.DecimalField: fields[f].max_digits = max_digits fields[f].decimal_places = decimal_places if field_class == models.CharField: fields[f].max_length = max_length for field_name, field_instance, function in self.time_series_functions: fields[field_name] = field_instance self.TimeSeriesModel = type(self.name, (models.Model,), fields) # next make sure that the tables exist in the database. if not, build them. from django.db import connection try: cursor = connection.cursor() cursor.execute("SELECT * FROM {} LIMIT 1".format(self.name)) except ProgrammingError: # Looks like the table doesn't exist! Let's build it! from django.db import connection from django.db.backends.base.schema import BaseDatabaseSchemaEditor schema_editor = BaseDatabaseSchemaEditor(connection) with schema_editor: schema_editor.create_model(self.TimeSeriesModel)