F
F
froosty2015-12-17 16:37:19
Python
froosty, 2015-12-17 16:37:19

How in the before_update event in SQL Alchemy to process only the direct change of fields, and the fields-links?

Good day. There is such a task. There are Category and Product models. There is a "many-to-many" relationship between them. It is necessary to hang a handler with def. on the before_update event for the category. additional actions. Actually, in a truncated form, it looks like this:

category_product = db.Table(
    'catalog_category_product',
    db.Column('id', db.Integer(), db.Sequence('catalog_category_product_id_seq'), primary_key=True, nullable=False),
    db.Column('category_id', db.Integer(), db.ForeignKey('catalog_category.id', ondelete='CASCADE'), nullable=False),
    db.Column('product_id', db.Integer, db.ForeignKey('catalog_product.id', ondelete='CASCADE'), nullable=False),
)


class Product(db.Model):
    __tablename__ = 'catalog_product'
    id = db.Column('id', db.Integer(), db.Sequence('catalog_product_id_seq'), primary_key=True, nullable=False)
    category_products = db.relationship('Category', secondary=category_product,
                                        backref=db.backref('category_products', lazy='dynamic'))
    # ...


class Category(db.Model, BaseNestedSets):
    __tablename__ = 'catalog_category'
    id = db.Column('id', db.Integer(), db.Sequence('catalog_category_id_seq'), primary_key=True, nullable=False)
    # ...


def before_update_category(mapper, connection, target):
    # Какие-то действия

event.listen(Category, 'before_update', before_update_category)

The problem is the following. If I execute this code:
"""
product - instance of Product
category - instance of Category
"""
product.category_products.append(category)

then the before_update_category function still fires. Empirically, it was revealed that this happens due to the fact that orm considers the category.product_category field to be changed. I understand that before performing additional actions, I need to check if any of the main fields have changed, or only fields with links. Actually it should be something like:
def is_instance_really_updated(category):
    # Какой-то код
    #return bool result

def before_update_category(mapper, connection, target):
    if is_instance_really_updated(target):
        # Какие-то действия

But I can't figure out what should be in the is_instance_really_updated method in this case. Help please =)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question