Alok
Alok

Reputation: 789

Representation of arrays in MySQL

We are doing a project which is using the django framework with MySQL database. I wanted to make an array in the models by using

CommaSeparatedIntegerField.

eg:

class MyModel(models.Model):
values = CommaSeparatedIntegerField(max_length = 200)

How will this be represented in MySQL?

Upvotes: 0

Views: 121

Answers (3)

Anup
Anup

Reputation: 753

I had to do something of this sort some time back and what i did was used the way suggested here.

http://justcramer.com/2008/08/08/custom-fields-in-django/

 from django.db import models
 class SeparatedValuesField(models.TextField):
       __metaclass__ = models.SubfieldBase

       def __init__(self, *args, **kwargs):
           self.token = kwargs.pop('token', ',')
           super(SeparatedValuesField, self).__init__(*args, **kwargs)

       def to_python(self, value):
           if not value: return
           if isinstance(value, list):
              return value
           return value.split(self.token)

      def get_db_prep_value(self, value):
            if not value: return
            assert(isinstance(value, list) or isinstance(value, tuple))
            return self.token.join([unicode(s) for s in value])

     def value_to_string(self, obj):
            value = self._get_val_from_obj(obj)
            return self.get_db_prep_value(value)

Upvotes: 0

Mr_Spock
Mr_Spock

Reputation: 3835

First normal form

You might be better off avoiding that: https://en.wikipedia.org/wiki/1NF

Upvotes: 1

Devart
Devart

Reputation: 122042

There are no arrays in MySQL. If you store array as a comma separated string, then you will have problems with selecting, modifying data and optimization.

So, I'd suggest you to store items in table's rows.

Upvotes: 2

Related Questions