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.
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.