efjfnewfj efjfnewfj - 7 months ago 21
Python Question

A list model field for Models.Model

I'm looking for a field that I can use to be defined in my model which is essentially a list because it'll be used to store multiple string values. Obviously CharField cannot be used.

Answer

You are describing a many-to-one relationship. This should be modeled by an extra Model having a CharField to store the string and ForeignKey to your main Model (as @Kujira has already pointed out):

class YourModel(models.Model):
    pass

class String(models.Model):
    your_model = models.ForeignKey('YourModel', related_name='strings')
    string = models.CharField('String', max_len=..., ...)

Now you can add strings to an instance of YourModel:

ym = YourModel.objects.create()
ym.strings.create(string='string1')
ym.strings.create(string='string2')