Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How do I create a model dynamically?

How do I create a model dynamically upon uploading a CSV file? I have done the part where it can read the CSV file.

I'm trying to create a web application where different kind of users can upload their own CSV files for anomaly detection. And then shape the model based on the CSV file the user uploads.

like image 955
Django newbie Avatar asked Feb 15 '26 12:02

Django newbie


1 Answers

This doc explains very well how to dynamically create models at runtime in Django. A snippet of the main example of doing so:

Django model:

class Animal(models.Model):
    name = models.CharField(max_length=32)

And here is the equivalent class built using type():

attrs = {
    'name': models.CharField(max_length=32),
    '__module__': 'myapp.models'
}
Animal = type("Animal", (models.Model,), attrs)

However, as you will see after looking at the document, it is quite complex and cumbersome to do this. I would not recommend doing this and believe it is quite likely you can determine a model ahead of time that is flexible enough to handle the CSV. This would be much better practice since dynamically changing the schema of your database as your application is running is a recipe for a ton of bugs in your code.

like image 168
Rohan Varma Avatar answered Feb 17 '26 02:02

Rohan Varma



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!