'sqlalchemy relationship and classmethods and not only

I have a problem that I can't solve((( Sample code below...

from sqlalchemy import Column, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.types import Integer, String, Text

Base = declarative_base()

class Model(Base):
    __abstract__ = True

    @classmethod
    def need_run(cls):
        pass

class Profile(Model):
  __tablename__ = 'profile'

  id = Column('id', Integer, primary_key=True)
  email = Column('email', String(length=128), unique=True, index=True)
  password = Column('password', String(length=255), index=True)
  messages = relationship('Message', lazy='select')

class Message(Model):

  __tablename__ = 'message'
  id = Column('id', Integer, primary_key=True)
  profile_id = Column('profile_id', Integer, ForeignKey('profile.id', ondelete='CASCADE'))
  title = Column('title', String(length=128), unique=True, index=True)
  body = Column('text', Text, index=True)
  1. Through the message attribute, i want to access the Message class to run the need_run method
  2. Through the profile_id attribute, i want to access the Profile class to run the need_run method

Is it possible?



Solution 1:[1]

It should be possible but you probably want to change your relationship to include a backref:

class Profile(Model):
    #...
    messages = relationship('Message', lazy='select', backref="profile")

Then you can access messages from a profile like:

for msg in some_profile.messages:
    msg.need_run()

And you can access a profile from a message like:

some_message.profile.need_run()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ian Wilson