Skip to content

ModelSchema

Ryan Vinzent edited this page Sep 21, 2020 · 4 revisions

ModelSchema is the mechanism by which tables are dynamically added to the database. There is one field on the model: name.

Create a new table by saving an instance of ModelSchema. The name of the generated Django model will be CamelCased and the table name will be generated sin a similar fashion to the naming strategy in Django. It will be prepended with the app_label and converted to snake_case.

Note: the app_label can be configured by setting the USE_APP_LABEL configuration setting.

from dynamic_models.models import ModelSchema, FieldSchema

car_schema = ModelSchema.objects.create(name='car')

assert car_schema.model_name == 'Car'
assert car_schema.app_label == 'dynamic_models'

Car = car_schema.as_model()

#  equivalent to this static Django model declaration

class Car(models.model):
    ...fields...

ModelSchema Reference

Properties

name: models.CharField

The name of the model. This will be used to generate the Django Model class name as well as the name in the. database table. The field currently has max_length of 32.

model_name: string

The string to be used as the class name when generating the Model class.

initial_model_name: string

The model_name when the instance was initialized.

db_table: string

The name of the table generated by this ModelSchema instance.

app_label: string

The configured app_label where the dynamic model will be registered. This defaults to dynamic_models but it can be configured by setting the USE_APP_LABEL configuration option.

Methods

as_model() -> Model

Generate a subclass of Django's models.Model using the current ModelSchema instance and related FieldSchema objects.

get_registered_model() -> bool

Get the current registered model from Django's app registry. This will be a class generated by a call to as_model(), which will register the class with Django.

is_current_model(model: Model) -> bool

Returns a boolean of whether the provided model is the "latest" version. If the model was generated by a prior as_model() call, and the ModelSchema has since been updated, this will return False.

Class Methods

get_model_name(name: string) -> string

Returns a CamelCase version of the string passed in to the