Django create / modify tables on demand

I was looking for a way to define database tables and modify them using the Django API.

For example, I would like to write code that directly manipulates a table DDL and allows me to define tables or add columns to a table on demand programmatically (without running syncdb). I understand that django-south and django-evolution may come to mind, but I really do not think of these tools as tools designed to be integrated into the application and used by the end user ... rather, these tools are utilities used to updating database tables. I am looking for something where I can do something like:

class MyModel(models.Model):  # wouldn't run syncdb.. instead do something like below
    a = models.CharField()
    b = models.CharField()

model = MyModel()
model.create()  # this runs the create table (instead of a syncdb)

model.add_column(c = models.CharField())  # this would set a column to be added
model.alter()   # and this would apply the alter statement 

model.del_column('a')   # this would set column 'a' for removal 
model.alter()   # and this would apply the removal 

, API, , , , . , , . , , . , - - ?

(, , SQL , )

, - ...

+3
2

django, . (, ALTER, ), . django.core.management.commands.syncdb.

for app in models.get_apps():
        app_name = app.__name__.split('.')[-2]
        model_list = models.get_models(app)
        for model in model_list:
            # Create the model database table, if it doesn't already exist.
            if verbosity >= 2:
                print "Processing %s.%s model" % (app_name, model._meta.object_name)
            if connection.introspection.table_name_converter(model._meta.db_table) in tables:
                continue
            sql, references = connection.creation.sql_create_model(model, self.style, seen_models)
            seen_models.add(model)
            created_models.add(model)
            for refto, refs in references.items():
                pending_references.setdefault(refto, []).extend(refs)
                if refto in seen_models:
                    sql.extend(connection.creation.sql_for_pending_references(refto, self.style, pending_references))
            sql.extend(connection.creation.sql_for_pending_references(model, self.style, pending_references))
            if verbosity >= 1 and sql:
                print "Creating table %s" % model._meta.db_table
            for statement in sql:
                cursor.execute(statement)
            tables.append(connection.introspection.table_name_converter(model._meta.db_table))

connection.creation.sql_create_model. creation , , .py. django.db.backends.

ALTER, , , . ExtendedModelManager.

+1

.

Create/Alter.

+2

Source: https://habr.com/ru/post/1769044/


All Articles