简体   繁体   中英

Update SQLAlchemy orm object with changed python dict

Having issues with implementing a mutable dict that will react to changes in content. I have managed to setup SQLAlchemy to manage add and delete. However, changes to content of a stored dict doesn't "trigger" update of the SQLAlchemy db.

I found some other questions here on stackoverflow that suggested:

By default SQLAlchemy doesn't track changes inside dict attributes. To make it track changes, you can use the mutable extension:

I followed the example here How to implement mutable PickleTypes that automatically update on change

However, I can't get it to work. In my example, when I change from Column(PickleType) to Column(MutableDict.as_mutable(PickleType)) the SQLAlchemy session no longer finds the object. The code below illustrates what I'm trying to do.

The first code is where I set up the db and the second block I'm trying to add transactions to a person. I manage to add transactions and delete them but not change them. Hence, why I tried with the MutableDict class, but I don't seem to fully understand it.

Setup SQL db: (sqlalchemy_declarative.py)

from sqlalchemy import Column, ForeignKey, Integer, String, PickleType
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()


class MutableDict(Mutable, dict):

    @classmethod
    def coerce(cls, key, value):
        if not isinstance(value, MutableDict):
            if isinstance(value, dict):
                return MutableDict(value)
            return Mutable.coerce(key, value)
        else:
            return value

    def __delitem(self, key):
        dict.__delitem__(self, key)
        self.changed()

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        self.changed()

    def __getstate__(self):
        return dict(self)

    def __setstate__(self, state):
        self.update(self)


class Person(Base):
    __tablename__ = 'person_object'
    # Here we define columns for the table person
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    first_name = Column(String, nullable=False)
    last_name = Column(String, nullable=False)

    def __str__(self):  # prints when treated as string (for use interface)
        return f"Primary id: {self.id} \n" \
               f"First name: {self.first_name}"


class Transactions(Base):
    __tablename__ = 'transactions'
    # Here we define columns for the table address.
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    transactions = Column(MutableDict.as_mutable(PickleType))
    # transactions = Column(PickleType)
    person_object_id = Column(Integer, ForeignKey('person_object.id'))
    person_object = relationship(Person)

    def update(self, tmp_dict):
        for key, value in tmp_dict.items():
            print(key, value)
            setattr(self, self.transactions[f'{key}'], value)


def create_db():
    # Create an engine that stores data in the local directory's
    # sqlalchemy_example.db file.
    engine = create_engine('sqlite:///person.db')

    # Create all tables in the engine. This is equivalent to "Create Table"
    # statements in raw SQL.
    Base.metadata.create_all(engine)

Example code:

from sqlalchemy_declarative import Person, Base, Transactions
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

import sqlalchemy_declarative as sqlalchemy_declarative


def main():
    sqlalchemy_declarative.create_db()
    engine = create_engine('sqlite:///person.db')
    Base.metadata.bind = engine
    db_session = sessionmaker()
    db_session.bind = engine
    session = db_session()

    transaction1 = {'item1': 'banana',
                    'item2': 'apple',
                    'item3': 'sugar',
                    'item4': 'coke',
                    'item5': 'candy'}
    transaction2 = {'item1': 'pizza',
                    'item2': 'water'}

    new_obj = Person(first_name='Bob', last_name='Smith')
    session.add(new_obj)

    new_transaction = Transactions(transactions=transaction1, person_object=new_obj)
    session.add(new_transaction)

    new_transaction = Transactions(transactions=transaction2, person_object=new_obj)
    session.add(new_transaction)
    session.commit()

    test = session.query(Transactions).all()

    for tmp in test:
        print(type(tmp.transactions))
        print(tmp.transactions == transaction1)

    test2 = session.query(Transactions).filter(Transactions.transactions == transaction1).all()
    print(test2)

    transaction1 = {'item1': 'banana',
                    'item2': 'apple',
                    'item3': 'sugar',
                    'item4': 'coke',
                    'item5': 'pineapple'}
    test2.update(transaction1)
    session.commit()

    all_transactions = session.query(Transactions).all()

    for tmp in all_transactions:
        print(tmp.transactions)


if __name__ == '__main__':
    main()

However, the test2 filter doesn't find any transaction that matches the transaction1 dictionary. I suspect this has to do with the fact that the dict are stored as MutableDict and not Dict. But what do I do about that and how do I edit and change my transaction1 after I have added it.

TLDR: I want to change content in my dict that is stored as an ORM using SQLAlchemy.

I realised that I was able to work around my problem by simply not using the .filter method. Hence the example below works just fine.

    transaction1 = {'item1': 'banana',
                    'item2': 'apple',
                    'item3': 'sugar',
                    'item4': 'coke',
                    'item5': 'candy'}
    transaction2 = {'item1': 'pizza',
                    'item2': 'water'}

    new_obj = Person(first_name='Bob', last_name='Smith')
    session.add(new_obj)

    new_transaction = Transactions(transactions=transaction1, person_object=new_obj)
    session.add(new_transaction)

    new_transaction = Transactions(transactions=transaction2, person_object=new_obj)
    session.add(new_transaction)
    session.commit()

    test = session.query(Transactions).all()

    for tmp in test:
        print(tmp.transactions)

    new_transaction.transactions['item1'] = 'curry banana'
    session.commit()

    test = session.query(Transactions).all()

    for tmp in test:
        print(tmp.transactions)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM