mercredi 15 juillet 2015

insert if not exists else update peewee

Im trying to update a table if the row id exists in another table as user_id else create it

In the peewee documentation there is a get_or_create()method but I have been unsuccessful getting it to work

This code does what i want but it's hacky.

def example():
    form = forms.example()
    a_model = models.A.select()
    b_model = models.B.select()
    for foo in a_model:
        for bar in b_model:
            if foo.id == bar.user_id:
                update = A.update(x=form.baz.data, y=form.qux.data)
                update.execute()
                return something()
        else:
            models.B.create(x=form.baz.data,y=form.qux.data).where(stuff)
            return something()
    return sometihng_else()

This is how I unsuccessfully used get_or_create()

def get_or_create_example():
    form = forms.example()
    a_model = models.A.select()
    b_model = models.B.select()
    for foo in a_model:
        update = models.A.get_or_create(x=form.baz.data, y=form.qux.data).where(stuff)
        update.execute()
        return something()        
    return sometihng()

Any advice on where I went wrong would be appreciated.

Aucun commentaire:

Enregistrer un commentaire