I want a field in my Django model to store array data.
For instance consider a model that stores Student data. I want an array field that stores the marks of that student as an integer array. What can I do?
I am not using PostGreSQL so I cannot use ArrayField.
class Student(models.Model):
...
...
marks = models.?
Typically you don't. Even for PostgreSQL not advisable. Relational databases are usually better to work with scalar values in columns.
You can make a model Mark
, with a ForeignKey
[Django-doc] to Student
, for example:
class Student(models.Model):
# …
class Mark(models.Model):
mark = models.IntegerField()
student = models.ForeignKey(
Student,
related_name='marks'
on_delete=models.CASCADE
)
You can then create for example marks for a student:
student = Student.objects.create()
Mark.objects.create(student=stud, mark=7)
Mark.objects.create(student=stud, mark=8)
Then you access the Mark
objects of the student
with:
student.marks.all()