Skip to content
Advertisement

Update SQLAlchemy column of my referral when my own column changes

Any time my wallet_1 is been modified with +1 or any value, I want to get the value and add it into the wallet_2 of my referral wallet which is (Joshua wallet_2) as well as for wallet_2, if my wallet_2 is been modified with +1 or any value, I want to get the value and add it into the wallet_3 of my referral wallet which is (Joshua wallet_3).

def User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String)
    my_referral = db.Column(db.String) #referral = Joshua

def Wallet(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    wallet_1 = db.Column(db.Float, default=0.0)
    wallet_2 = db.Column(db.Float, default=0.0)
    wallet_3 = db.Column(db.Float, default=0.0)

Advertisement

Answer

First of all, why aren’t you using classes to build db models?

Based on what I managed to find on sqlalchemy docs, try this approach.

If you want to even update wallet3 based on what's happening in wallet2 – you can always set a few functions like update_wallet. Eg. update_wallet2 etc… which are gonna be referring to each other. I don’t have access to your application and whole environment, and from my point of view this is the most I can do to help. Stop speculating, overthinking it and just go and try setting up those functions, then test & debug till you success.

def update_wallet(context):
    return context.get_current_parameters()['wallet_1']

# every function gonna follow the same pattern
def update_wallet3(context):
    return context.get_current_parameters()['wallet_2']


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String)
    referral = db.Column(db.String)
    

class Wallet(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    wallet_1 = db.Column(db.Float, default=0.0)
    wallet_2 = db.Column(db.Float, default=0.0, onupdate=update_wallet)
    wallet_3 = db.Column(db.Float, default=0.0, onupdate=update_wallet3)

So, the update_wallet function is being triggered when INSERT or UPDATE statement occurrs on the wallet_1 column. It is retrieving the given value, and inserting/updating it for the wallet_2.

Just like I mentioned before, carefully try to read through the sqlalchemy docs. Good luck.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement