Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I was wondering if it's possible to store an array in a Django model?

I'm asking this because I need to store an array of int (e.g [1,2,3]) in a field and then be able to search a specific array and get a match with it or by it's possible combinations.

I was thinking to store that arrays as strings in CharField s and then, when I need to search something, concatenate the values(obtained by filtering other model) with '[', ']' and ',' and then use a object filter with that generated string. The problem is that I will have to generate each possible combination and then filter them one by one until I get a match, and I believe that this might be inefficient.

So, I hope you can give me other ideas that I could try.

I'm not asking for code, necessarily, any ideas on how to achieve this will be good.

I'd have two advices for you:

1) Use ArrayField if you are using PostgreSQL as your database. You can read more about ArrayField here .

2) Encode your array as JSON and store it either as a plain string or using a JSONField as found here .

I'd personally prefer option number 1 since that is the cleaner and nicer way but depending on what you are actually using to store your data that might not be available to you.

There is now a django support JSONField: docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/… Eduardo Feb 21, 2019 at 19:00 Django now supports the JSON field. Simply: models.JSONField(). docs.djangoproject.com/en/3.1/releases/3.1/… hkimani Aug 20, 2020 at 16:51
from django.contrib.postgres.fields import ArrayField
class Board(models.Model):
    pieces = ArrayField(ArrayField(models.IntegerField()))

However, it can only be available when using PostgreSQL for the database.

If you aren't using Postgres, I recommend Django's validate_comma_separated_integer_list validator.

https://docs.djangoproject.com/en/dev/ref/validators/#django.core.validators.validate_comma_separated_integer_list

You use is as a validator on a CharField().

I don't know why nobody has suggested it, but you can always pickle things and put the result into a binary field.

The advantages of this method are that it will work with just about any database, it's efficient, and it's applicable to more than just arrays. The downside is that you can't have the database run queries on the pickled data (not easily, anyway).

Pickle is unsafe, it is not marshalisation, it relies on a virtual machine to recreate object and this VM is Turing complete. So basically it can execute any arbitrary code, might be the reason why. – jlandercy Jul 10, 2021 at 5:06 @jlandercy How is that a problem here? If an attacker has access to your database such that they can insert pickled data intended to run arbitrary code, they probably also have the ability to ask the database itself to run arbitrary code. – al45tair Jul 11, 2021 at 7:49 Pickle is unsafe, it is well known but we still see false quick win relying on it and this generally breaks at some point because it is a very powerful vector of attack. Do you mean deliberately adding a vulnerability to a code because it easy is not a concern? – jlandercy Jul 11, 2021 at 16:24 @alastair That is not true. The attacker may only have access to the database and nothing else. Yes sure the data is entirely compromised, but the backend may not be. Storing pickled data will give the attacker much, much better freedom to do his work. And besides that, the attacker could only have a simple access of inserting data, nothing else. They could insert some malicious pickled data and boom, they have full access now. – HosseyNJF Aug 13, 2021 at 17:21 I've been using pickle since its inception. You are fine as long as you aren't pickling user input. It never broke anything, never had to replace it, code runs fine since decades (just make sure you migrate formats when switching between major versions) Pretty sure "don't use pickle" people do much gnarlier things with their code. This is just some low hanging fruit people like to cling on. – nurettin Oct 23, 2022 at 8:07

you can store a json and good to go with sub arrays of that JSON:

if (data != "attachmentto") {
        formData.append(data, this.recipe[data])
        console.log('rec data ', data)}
        else if (data == "attachmentto") {
          console.log('rec data434 ', this.recipe.attachmentto)
          var myObj = { name: this.recipe.attachmentto.name, age: 31, city: "New York" };
          let kokos = JSON.stringify(myObj);
          // this.recipe.attachmentto.name = this.recipe.attachmentto.name
          formData.append('attachmentto', kokos)

Django backend:

class Video(models.Model):
  objects = models.Manager()
  title = models.CharField(max_length=80)
  description = models.TextField(max_length=300)
  picture = JSONField(encoder=None)
  price = models.IntegerField(default=0)
  url = models.URLField()
  category = models.CharField(max_length=50)
  subcategory = models.TextField(max_length=50)
  attachmentto = JSONField(encoder=None)
  # attachmentto2 = models.JSONField()
  user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)

and result on backend API:

"id": 174, "title": "ads", "description": "ads", "picture": { "name": "https://v3.vuejs.org/logo.png" "price": 0, "user": 1, "rating_average": 0, "attachmentto": { "age": 31, "city": "New York", "name": [ "https://restdj.herokuapp.com/media/uploads/ftf_3_cJ0V7TF.png", "https://restdj.herokuapp.com/media/uploads/ftf_3.jpg"

I call it noicely(nicely). Notice that we send a JSON and we have a array in that JSON

Kokos is the full JSON disagned for djangoo:

  var myObj = { name: this.recipe.attachmentto.name, age: 31, city: "New York" };
let kokos = JSON.stringify(myObj);

formData.append('attachmentto', kokos)

Above; name: this.recipe.attachmentto.name is an array

Here is the array: "name": [

"https://restdj.herokuapp.com/media/uploads/ftf_3_cJ0V7TF.png",
                "https://restdj.herokuapp.com/media/uploads/ftf_3.jpg"
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.