0

So, My models.py has this model

class student(models.Model): ID = models.CharField(default='DUMMY_ID',primary_key=True,max_length=10) Score = models.CharField(default='DUMMY_Score',max_length=150) class = models.CharField(default='DUMMY_class',max_length=20)

and the requirement now is that a user (consider him to be admin/the director of the institute) should be able to add a new column to the database like section or rank or something.

so is there any way to add a new column to the table dynamically and if yes can you please explain it with an example as I am a beginner at Django.

DOUBT: if there's some way to do this, then will the above models.py have another entry (eg: rank= models.CharField(default='rank',max_length=20) after the change is made? and what data is filled for the previous entries in the new column?

Vinay Guda
  • 55
  • 1
  • 1
  • 9

1 Answers1

0

so is there any way to add a new column to the table dynamically

No.

You can not edit the database on the go, it needs migrations and Django/databases are just not made for this sort of thing. Your application has a bad design if you need to do this. If you explain further why you even need something like this, I can recommend some better design patterns, but for now the "next best thing" is probably JsonField that you can fill with random JSON data. So when you need to add rank to a student, you can just dump JSON like this to the JsonField:

{"rank": "value"}  

The other way (and probably a bit better) is to create a related model that holds all the extra properties.

class student(models.Model):
    ID = models.CharField(default='DUMMY_ID',primary_key=True,max_length=10)
    Score = models.CharField(default='DUMMY_Score',max_length=150)
    class = models.CharField(default='DUMMY_class',max_length=20)

class StudentProperty(models.Model):
    student = models.ForeignKey(student)
    key = models.CharField(max_length=128)
    value = models.CharField(max_length=256)

And then populate the StudentProperty with rank being the key and well, value being the value. You can create new objects from models dynamically, but not new fields on models.

wanaryytel
  • 3,352
  • 2
  • 18
  • 26