-
Notifications
You must be signed in to change notification settings - Fork 46
Introduction
Note: Many breaking changes were introduced in 0.2.0
. For 0.1.0
documentation, see here.
dynamic_models
consists of two models that can be used to introduce dynamic changes to the database at runtime.
Adding dynamic schema to the database is as simple as creating a new instance of ModelSchema
. A new Django model with the provided name will be generated and registered to Django's app registry. The dynamically generated model is accessible from the ModelSchema
instance's .as_model()
method. this model can be used in the same way that any other statically defined model is normally used.
from dynamic_models.models import ModelSchema, FieldSchema
car_schema = ModelSchema.objects.create(name='Car')
Car = car_schema.as_model()
Car.objects.create()
assert Car.objects.count() == 1
Creating records of ModelSchema
will create a new table in the database initially without any fields. Add fields to the database table by associating instances of FieldSchema
.
car_model_field = FieldSchema.objects.create(model_schema=car_schema, name='model', data_type='character')
car_year_field = FieldSchema.objects.create(model_schema=car_schema, name='year', data_type='integer')
# `as_model()` must be called again to regenerate the model class after a new field is added
Car = car_schema.as_model()
Car.objects.create(model='Camry', year=1997)
assert Car.objects.filter(model='Camry').count() == 1