Home > Net >  Keeping CharFields in array instead of multiple variables
Keeping CharFields in array instead of multiple variables

Time:10-05

Right now I'm using various variables to store fields, and it works well, but I'd like to move them to lists. Is there a way to do this?

What I have now:

lessonNameFirst = models.CharField('8:30-10:00', max_length = 50)
additInfoFirst = models.CharField('Additional info', max_length = 50)

lessonNameSecond = models.CharField('10:15-11:45', max_length = 50)
additInfoSecond = models.CharField('Additional info', max_length = 50)

lessonNameThird = models.CharField('12:30-14:00', max_length = 50)
additInfoThird = models.CharField('Additional info', max_length = 50)

lessonNameFourth = models.CharField('14:10-15:40', max_length = 50)
additInfoFourth = models.CharField('Additional info', max_length = 50)

What I'm looking for:

lessonName = [
    models.CharField('8:30-10:00', max_length = 50),
    models.CharField('8:30-10:00', max_length = 50),
    models.CharField('8:30-10:00', max_length = 50),
    models.CharField('8:30-10:00', max_length = 50)
]

additInfo = [
    models.CharField('Additional info', max_length = 50),
    models.CharField('Additional info', max_length = 50),
    models.CharField('Additional info', max_length = 50),
    models.CharField('Additional info', max_length = 50)
]

CodePudding user response:

You can use the ArrayField if you're using PostgreSQL as the database.

from django.contrib.postgres.fields import ArrayField

class ModelName(models.Model):
    lessonName =  ArrayField(models.CharField(max_length = 50))
    additInfo = ArrayField(models.CharField(max_length = 50))
]

Refer here for connecting Django with PostgreSQL.

  • Related