Dynamic models in Django - Juergen Schackmann

Tags: django, djangocon

The classical approach in django is:

Code development

You create models.


Tables and columns are created with syncdb.


Models and db tables are populated.

This means that models are pretty much static. There is no way to modify them at runtime based on user interactions. You can get something working with for instance hstore in postgresql (see the postgresql talk).

His usecase is for medical forms. The contents of those forms should be able to be defined inside the system. There are strict processes for installing medical software, so you cannot just release a new version with a new field. So you must get it to work at runtime.

The solution could be to use dynamic models, models created at runtime. Sometimes configuration by subject matter experts is better than code customization by developers. Also, dynamic models reduce the number of deployment cycles.

He has some criteria:

  • Performance.

  • Querability, which means the standard django query stuff should work.

  • Django standard tool integration (admin, cache, and so).

  • Supported DB backends. If possible, support all django DB backends.

  • Complexity/maintainability.

There are a couple of possible solutions:

Entity attribute value (EAV)

Colums are stored in separate table rows. Instead of a table having attributes, a table has an attribute table with values. There are at least two apps that provide this. The performance is a problem here.

Serialized dictionary

For instance one of the Django JsonField apps. A lot of what is normally database work is now moved to the application. You’ll really have to create custom logic in your app to take care of it.

Runtime schema updates

Update models at runtime with syncdb of some South functionality or Andrew’s new schema migrations for Django work. There are a couple of apps that do this. He also created his own one. The best one seems to be django-mutant.

Database-specific solutions

Hstore, django-nonrel. Drawback: it doesn’t work with all database backends, of course.

In the end, the runtime schema updates approach looks like the best one.

For more reading: https://code.djangoproject.com/wiki/DynamicModels

vanrees.org logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):