简体   繁体   中英

How do I store a string in ArrayField? (Django and PostgreSQL)

I am unable to store a string in ArrayField. There are no exceptions thrown when I try to save something in it, but the array remains empty. Here is some code from models.py :

# models.py
from django.db import models
import uuid
from django.contrib.auth.models import User
from django.contrib.postgres.fields import JSONField, ArrayField


# Create your models here.
class UserDetail(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    key = models.CharField(max_length=50, default=False, primary_key=True)
    api_secret = models.CharField(max_length=50)
    user_categories = ArrayField(models.CharField(max_length = 1000), default = list)

    def __str__(self):
        return self.key

class PreParentProduct(models.Model):
    product_user = models.ForeignKey(UserDetail, default=False, on_delete=models.CASCADE)
    product_url = models.URLField(max_length = 1000)
    pre_product_title = models.CharField(max_length=600)
    pre_product_description = models.CharField(max_length=2000)
    pre_product_variants_data = JSONField(blank=True, null=True)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    def __str__(self):
        return self.pre_product_title

I try to save it this way:

        catlist = ast.literal_eval(res.text)
        for jsonitem in catlist:
            key = jsonitem.get('name')
            id = jsonitem.get("id")
            dictionary = {}
            dictionary['name'] = key
            dictionary['id'] = id
            tba = json.dumps(dictionary)
            print("It works till here.")
            print(type(tba))
            usersearch[0].user_categories.append(tba)
            print(usersearch[0].user_categories)

        usersearch[0].save()
        print(usersearch[0].user_categories)

The output I get is:

It works till here.
<class 'str'>
[]
It works till here.
<class 'str'>
[]
[]

Is this the correct way to store a string inside ArrayField? I cannot store JSONField inside an ArrayField, so I had to convert it to a string.

How do I fix this?

Solution to the append problem.

You haven't demonstrated how your usersearch[0] I suspect it's something like this:

usersearch = UserDetail.objects.all()

If that is so you are making changes to a resultset, those things are immutable. Try this you will see that the id is unchanged too:

usersearch[0].id = 1000
print usersearch.id

But this works

usersearch = list(UserDetail.objects.all())

and so does

u = usersearch[0]

Solution to the real problem

user_categories = ArrayField(models.CharField(max_length = 1000), default = list)

This is wrong. ArrayFields shouldn't be used in this manner. You will soon find that you need to search through them and

Arrays are not sets; searching for specific array elements can be a sign of database misdesign. Consider using a separate table with a row for each item that would be an array element. This will be easier to search, and is likely to scale better for a large number of elements

ref: https://www.postgresql.org/docs/9.5/static/arrays.html

You need to normalize your data. You need to have a category model and your UserDetail should be related to it through a foreign key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM