7

I want to store a list in database of Django .which model field i should use and how. I tried ArrayField but it does not take list.

from django.contrib.postgres.fields import ArrayField
from django.db import models
class signup(models.Model):
    userid=models.CharField(max_length=10)
    password=models.CharField(max_length=10)
    list=ArrayField(models.IntegerField(null=True,blank=True),size=5,null=True)
    score=models.IntegerField(default=0)
Kunal Kakade
  • 107
  • 2
  • 10
  • ArrayField is specific to PostgreSQL. What does you list look like? Is it all integers? Are you going to need doing queries on the list? – Selcuk Feb 12 '16 at 03:06
  • the list consists of integers. I need to read and modify each element in list – Kunal Kakade Feb 12 '16 at 09:19
  • 6
    You can try storing them in a `CharField` by converting the list to a string while storing (`";".join(my_list)`) and back to a string while reading (`my_model.list.split(";")`) – Selcuk Feb 13 '16 at 04:38

1 Answers1

0

You need to define a default type for the ArrayField(), in this case, it needs to be defined as default=list.

Also, you can't use keywords such as str,list,int, etc. as names of variables!

Your code should look something like this:

from django.contrib.postgres.fields import ArrayField
from django.db import models
class signup(models.Model):
    userid=models.CharField(max_length=10)
    password=models.CharField(max_length=10)
    lst=ArrayField(
        models.IntegerField(null=True,blank=True),
        size=5,
        default=list,
        null=True
    )
    score=models.IntegerField(default=0)
J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94
Pazzio
  • 1