Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Models Django 2019

Okay, I know there are threads all over the place from outdated ways to make dynamic django models meaning, they are altered by a user at runtime of the application. I am not finding a solid solution outside of using custom SQL to make dynamic tables in my project, so I am hoping there is a way to dynamically create a model during runtime, so it can be used in Django's ORM.

So far in the last few weeks of checking, this seems either overly complicated or impossible for my situation

For example and in brevity, I have a unit_declaration model, which holds column names for each Property a client 'owns'. I then take those column names and currently create a custom SQL query to build a unit table based on those columns for each property (i.e. _[PROPERTYID]_units). I want to be able to not use custom SQL to generate the creation of client property-unit tables at runtime, how is this possible (and I need a real example because nothing is making sense to me elsewhere)?

I can certainly provide code as to what I am doing so far, and I completely unvderstand this is the point of SO, but I am hitting a block and need a suggestion and believe a random post of code is unhelpful as it shows only what I have described. I learned today that Django's Foreign Keys are very convenient, and I cannot use them with customly declared SQL tables (outside of Django's ORM), how do I make a runtime-based model?

I have looked at the PyPi package of django-dynamic-models, but it seems outdated as the latest release was 2014. Is there a better option or would you suggest I stick with custom SQL queries to make my dynamic tables for my project?

like image 276
ViaTech Avatar asked Jun 23 '26 22:06

ViaTech


1 Answers

If you use Postgresql, the best solution may just be adding a JSONField. It can be queried within the ORM, and can add a ton of flexibility without requiring new tables or a huge amount of custom code for dynamic models.

Here are a couple examples of its use.

Update: With modern versions of django you can use JSONField with the majority of its benefits regardless of that database backend you use!

like image 102
djangomachine Avatar answered Jun 26 '26 11:06

djangomachine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!