Package: django-dynamic-models-readonly
django-dynamic-models-readonlyOverviewDynamic Django models readonly allow users to define, edit, and populate their own database tables and apply runtime schema changes to the database.django-dynamic-modelsis loosely based on theruntime dynamic modelstalk from DjangoCon 2011. The basic concept involves around dynamic class declaration using the built-intypefunction. We usetypeto dynamically declare new Django models at runtime, and it is the goal of this project to provide a simple API to allow developers to get started with runtime dynamic models quickly.This package provides abstract models to help Django developers quickly implement dynamic runtime models for their specific use case while the runtime schema changes and Django's model registry are handled automatically. The schema changes are applied in pure Django,withoutthe migrations framework, so none of your dynamic models will affect your migrations files at all.InstallationInstalldjango-dynamic-model-readonlyfrom PyPi with:pip install django-dynamic-model-readonlyThen, add'dynamic_models'anddjango.contrib.contenttypestoINSTALLED_APPS.Note:Django's Content Types app is currently required, although this dependency may possibly removed in the future.INSTALLED_APPS=[...'dynamic_models','django.contrib.conttenttypes']UsageTo begin, simply subclassAbstractModelSchemaandAbstractFieldSchemafromdynamic_models.models. The abstract models will still work if no additional fields are provided. The simplest way to get started with dynamic models would be to add subclasses to your app'smodels.py, and run migrations. Then, new models can be created dynamically by creating instances of model schema and field schema models.fromdynamic_models.modelsimportAbstractModelSchema,AbstractFieldSchemaclassModelSchema(AbstractModelSchema):passclassFieldSchema(AbstractFieldSchema):passNow, run the migration commands:$ python manage.py makemigrations
> ... making migrations ...

$ python manage.py migrate
> ... migrating ...Creating dynamic modelsCreating a dynamic model is as simple as creating a new instance of your concrete model schema class.AbstractModelSchemaprovides a single field. Thenamefield will be used to generate the class name and the name of the database table. Once created, theas_modelmethod can be used to retreive the dynamic model class.Note:Thenamefield hasunique=Trueby default to help enforce unique table names generated by theAbstracModelSchemainstance. To use a different table naming scheme, thedb_table(and probablymodel_name) properties should be overridden. Care should be taken that it is not possible to generate the samedb_tablefrom different instances ofAbstractModelSchema.The default model_name will beCarand the default table_namemyapp_carwhere "myapp" is the app label. The table name and model name are derived from thenamevalue.car_model_schema=ModelSchema.objects.create(name='car')Car=car_model_schema.as_model()assertissubclass(Car,models.Model)# The dynamic model can now be used to create Car instancesinstance=Car.objects.create()assertinstance.pkisnotNoneAdding fieldsCreating field schema to add to models is quite similar to creating dynamic models.AbstractFieldSchemaprovides two fields,nameanddata_type, and they are responsible for naming the database column and choosing which Django field to add to the dynamic model. Fields are not attached to any dynamic model when they are created, so the same field can be applied to any number of dynamic models. The constraints applied to the field, however, are specific for each model-field pair. Currently supported data types are returned by theget_data_typesmethod on subclasses ofAbstractModelSchema. Currently, supported data types and their corresponding Django field classes are listed below:Note: The value ofdata_typeis not editable while data migrations are not supported.Data TypeDjango FieldcharacterCharFieldtextTextFieldintegerIntegerFieldfloatFloatFieldbooleanBooleanFielddateDateTimeFieldcar_model_schema=ModelSchema.objects.create(name='car')color_field_schema=FieldSchema.objects.create(name='color',data_type='character')The color field is still completely independent of the Car model, and it has not been added to any database tables. Like normal CharFields, a max_length must be defined for the character data type. Add a field to a dynamic model with theadd_fieldmethodcolor=car_model_schema.add_field(color_field_schema,null=False,unique=False,max_length=16)Field constraints can be added when a field schema is attached to a model schema. Now, the new field can be used as you normally would in Django. Be sure to grab
the lastest version of the dynamic model after changing schema orOutdatedModelErrorwill be raised on save.Car=car_model_schema.as_model()red_car=Car.objects.create(color='red')assertred_car.color=='red'# This will raise an error because the 'color' field is requiredanother_car=Car.objects.create()Change the schema with 'update_field' to allow null. Null columns cannot currently be changed to not null because a default value will be required to fill the null spaces. This limitation should be removed when default values are implemented.Existing field schema can be edited or removed with theupdate_fieldandremove_fieldmethods.car_model_schema.update_field(color_field_schema,null=True)car_model_schema.remove_field(color_field_schema)Supportdjango-dynamic-modelsis tested on Python 3.6+ with Django 2.0+ReferenceAbstractModelSchemaFieldsnameThe value of name deterimines the model name and table name of the dynamic model. It has theuniqueconstraint applied by default, but can be removed if a custom naming scheme has been implemented to prevent duplicate table and model names.Methodsas_model()Return the dynamic model generated by the model schema instance.get_fields()Return allModelFieldSchemainstances attached to this model.get_field_for_schema(field_schema)Return theModelFieldSchemainstance for this model schema and the provided field schema arugument.add_field(field_schema, **options)Add a field to this dynamic model by creating a new instance ofModelFieldSchema. Takes the field schema instance as the first argument and optionally any constraints applied to this field. Valid constraints arenull,unique, andmax_lengthif the field's data type requires.update_field(field_schema, **options)Update an existing field with new contraints. Currently, fields cannot be changed fromnull=Truetonull=False.remove_field(field_schema)Remove a field from the dynamic model.is_current_model(model)ReturnsTrueif the provided model is current with the latest schema andFalseif the schema has since changed from when the model was generated. This does not work on unsaved schema instances.destroy_model()Purges the dynamic model from the app registry and the database without deleting the schema instance. There are few use cases for calling this method manually.AbstractFieldSchemaFieldsnameThe name of the field. Used to generate the database column name. Names should not start with an underscore to avoid potentially clashing with private attributes on the generated models.data_typeUsed to determine the Django model field to used on the dynamic model. See above for a list of valid data types.Methodsget_data_types()Return a list of available data type options.update_last_modified()Marks all related model schema objects as changed, forcing the dynamic model to be redefined the next timeas_modelis called.