0

I'm trying to do the following: loop through a series of records, if one already exists, I update it. If it doesn't exist, I add it.

For some reason, the adding is working fine, but the updating is not occurring. here's the code:

for interchange in data:
    ltype='asdf'
    plink='qwer'

    e = Part.query.filter_by(interchange=interchange, light_type=ltype).first()
    if e is None:
        notpresent = notpresent + 1
        p = Part(interchange=interchange,light_type=ltype,partslink=plink,ptype=ptype)
        db.session.add(p)
    else:
        present = present + 1
        e.partslink = plink
        e.ptype = ptype

db.session.commit()

I print out the present and notpresent variables and both are > 0.

Am I handling the update part incorrectly when the record is found? That portion is not getting saved.

RailsTweeter
  • 1,625
  • 3
  • 18
  • 33

1 Answers1

0

you are missing a line:

# ...
else:
    present = present + 1
    e.partslink = plink
    e.ptype = ptype    
    db.session.add(e)  # here 'add' is adding changes to the session, not a new item.

you cannot commit changes if you do not register them.

Attack68
  • 4,437
  • 1
  • 20
  • 40
  • are you sure? I was referencing the previous answer here: https://stackoverflow.com/questions/6699360/flask-sqlalchemy-update-a-rows-information – RailsTweeter May 02 '19 at 18:49
  • Actually i went ahead and tried it and it throws an error. Object is already attached to session. – RailsTweeter May 02 '19 at 19:05
  • Ok, yes I agree, actually, the object `e` is in a `persistant` state since you have queried it and it already exists in the database, so will react to changes. However, adding an object doesn't usually return an error, I use it the way above to be more explicit and it works. Do you have another db session? Also in the loop `e` is overwritten for each `interchange` before you commit, so I wonder if that act removes the `persistent` state objects from the session and thats why they don't commit? Just speculating – Attack68 May 02 '19 at 19:28
  • ive tried committing each time in the loop too. same result. – RailsTweeter May 02 '19 at 19:40
  • Im left to wonder if your `Part.query` is not operating with another defined sessionscope (i.e. the previous error you raised). Have you tried.. `e = db.session.query(Part).filter(Part.interchange==interchange, Part.light_type==ltype).first()` that way at least you can be sure you are querying with the same session. – Attack68 May 02 '19 at 19:47