-1

Im trying too save info to an ArrayField by using append. According to this post it should be possible but i cant get it to work. Im not creating a new object, it already exists i just need to append additional info to the ArrayField

Code snippet:

def isInDatabase(catInfo):
    cat = catagories.objects
    catName = str(catInfo)
    iban = catInfo.getIban()
    try:
        cat.get(Naam = catName)

    except ObjectDoesNotExist:
        print catName, 'is not in database'
        # NOTE: create catagory
        p = cat.create(Naam = catName, Rekening = [iban])
        print catName, 'Has been stored in the database with', iban
    else:
        ibanList = cat.get(Naam = catName).Rekening
        editCat = cat.get(Naam = catName)
        print catName,'is in db, the following ibans are stored:\n\n', ibanList,'\n\n'
        if iban in ibanList:
            print iban,'is already in the list\n'
        else:
            ibanList.append(iban)
            editCat.save()
            print 'Updated list for',catName,'with -->',iban,'\nlist is now -->', ibanList,'\n'

the editCat.save() is the save command thats not saving.

models.py

class catagories(models.Model):
    Naam = models.CharField(max_length=10)
    Rekening = ArrayField(models.CharField(max_length = 34), blank = True)

    def __str__(self):
        return self.Naam

So what modifications do i need to make to get it to save it to the database. I don't get any error, so the script runs fine but it doesn't save to the database.

Community
  • 1
  • 1
Kevin
  • 37
  • 10

2 Answers2

0

This is the problem code:

ibanList = cat.get(Naam = catName).Rekening
editCat = cat.get(Naam = catName)
...
ibanList.append(iban)
editCat.save()

The editCat remains unchanged. Use call to database only once and then get ibanList from the object you want to edit.

editCat = cat.get(Naam = catName)
ibanList = editCat.Rekening
Thyrst'
  • 2,253
  • 2
  • 22
  • 27
0

When you initialize editCat with editCat = cat.get(Naam = catName), you actually create new variable, which is not associated with ibanList. What you need to do is to change already retrieved value. Possible solution could be

editCat = cat.get(Naam = catName)
editCat.Rekening.append(iban)
editCat.save()

Another issue that worth to be mentioned is the presence of redundant db calls. Everytime you call get, you actually make new request on db (to be precise when queryset is evaluated). It would be better to retrieve value from db only once and operate over it.

AskhatOmarov
  • 39
  • 2
  • 7