[Fixed]-Using dynamic models in Django framework

5👍

There is a wiki page on creating models dynamically, although it has been a while since it was last updated:

DynamicModels Django

There are also a few apps that are designed for this use case, but I don’t think any of them is being actively maintained:

Django Packages: Dynamic models

I understand that if you are already committed to Django this isn’t very helpful, but this a use case for which Django isn’t really good. It might be more costly to fight against the abstractions provided by Django’s model layer, than to just use psycopg2 or whatever other adapter is appropriate for your data.

Depending on what sort of operations you are going to perform on your data, it may be also more reasonable to use a single model with an indexed field that allows you to distinguish in which table that row would be and then sharding the data by that column.

If you still need to do this, the general idea would be:

  1. Create a metaclass that extends Django’s ModelBase. This metaclass you would use as a factory for your actual models.

  2. Consider stuff mentioned on that wiki page, like circumventing the app_label issue.

  3. Generate and execute the sql for the creation of the model as also shown on the wiki page.

Leave a comment