Is it possible to store an array in Django model?

后端 未结 5 1702
日久生厌
日久生厌 2020-12-09 02:11

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

5条回答
  •  暖寄归人
    2020-12-09 03:02

    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"
                ]
    

提交回复
热议问题