Reputation: 501
I have a mysql database and am storing a list. Im currently storing it as a CharField but dont know if this is the best way to do it. I know that I should be using an ArrayFeild if my db was postgres, but its MYSQL.
I was content with this solution till I realized that the data was being stored like this:['COM', 'CRI', 'CUL', 'FOO']
whereas id expect it to be stored like this:[['COM'], ['CRI'], ['CUL'], ['FOO']]
.
forms.py
TOPICS = (
('ANI', 'Animals'),
('ART', 'Art'),
('COM', 'Communication'),
)
topics = forms.MultipleChoiceField(choices=TOPICS, required=False,
widget=forms.CheckboxSelectMultiple())
models.py
topics = models.CharField(max_length=200, default='')
How the data is stored in my db:
['COM', 'CRI', 'CUL', 'FOO']
Thank you.
Upvotes: 1
Views: 80
Reputation: 94
Nah thats a bit tricky. I had the same issue. I tried to do it with stuff like toString etc. I ended up in using a JSONField. So u can throw everything into a var and when u save this Django converts this to a JSONField in DB. If u load it from ur Database u can access the Values like always. U can loop it or whatever u want to do with it
In models.py
import jsonfield
class Example(models.Model):
example = jsonfield.JSONField()
So this works fine for me, if u need anything else let me know. pip install django-jsonfield The pip command.
If u need some more Examples or a Code Example let me know.
Upvotes: 2
Reputation: 931
Let the Django store it like this, you can later manipulate the list to convert it into the list of lists like:
>>>lst = ['COM', 'CRI', 'CUL', 'FOO']
>>>[[i] for i in lst]
[['COM'], ['CRI'], ['CUL'], ['FOO']]
Upvotes: 1