Separation between data and logic for sqlalchemy models

607 Views Asked by At

In the following example, should I keep the get_friend method inside my class or should I move it outside because I want to separate data structure from business logic ? What's the best practice ? Don't be biased by the class being small, it's just an example but the class could be much bigger.

from sqlalchemy import Column, Integer, String, Float, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class User(Base):
    id = Column("id", Integer, primary_key=True)
    friends = relationship("Friends")

    def get_friend(self, friend_name):
        for friend in self.friends:
            if friend.name == friend_name:
                return friend
        return None
1

There are 1 best solutions below

0
Amit Joshi On

I never used python and answering this only in terms of DAL and BLL.

The User is your Persistence Model if I am not wrong. Ideally, it should handle only persistence concerns. It should not handle the Domain logic; that part should move to Business Logic layer or your Service class.

Well, there are no any hard rules laid down anywhere for this; but there are "good practices"/"recommendations"/"paradigms"/"patterns". These are defined based on wider experience of large community.

So, you better consider moving that method to your BLL.