from .models import Portfolio ACTION_FIELD_MAP = { 'like': 'likers', 'scrap': 'scrappers', } class PortfolioBeforeRelCheckService: @staticmethod def check_user_portfolio_rel(action_type: str, portfolio: Portfolio, user): action = ACTION_FIELD_MAP.get(action_type) if not action: raise ValueError(f"'{action_type}' is unsupported action type") if getattr(portfolio, action).filter(id=user.id).exists(): return True else: return False class PortfolioStateChangeService: @staticmethod def change_user_portfolio_rel(action_type: str, portfolio: Portfolio, user, add=True): action = ACTION_FIELD_MAP.get(action_type) if not action: raise ValueError(f"'{action_type}' is unsupported action type") user_method = getattr(getattr(portfolio, action), 'add' if add else 'remove') user_method(user) @staticmethod def change_count_portfolio_state(action_type: str, portfolio: Portfolio, add=True): action = ACTION_FIELD_MAP.get(action_type) if not action: raise ValueError(f"'{action_type}' is unsupported action type") field_name = action_type + '_count' current_count = getattr(portfolio, field_name) now_count = current_count+1 if add else max(current_count-1, 0) setattr(portfolio, field_name, now_count) portfolio.save(update_fields=[field_name])