1

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.?
1
  • Typically you don't. Even for PostgreSQL not the best way. Usually you make a model Mark, with a ForeignKey to Student. Commented Aug 4, 2020 at 21:08

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively, we can also use the jsonfield python library. We can do the following, from jsonfield import JSONField class Student(models.Model): ... ... data = JSONField(default = list) More can be found out at (pypi.org/project/jsonfield)
@Adhishwar: I would advise not to do this. A JsonField is behind the curtains just a CharField with transparent wrapping between the string/data. As a result the database does not know what it stores. You thus can not order Students by average grade for example with a database query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.