Advertisement
Arexils

sqlalchemy orm mixin

Aug 10th, 2022
670
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.31 KB | None | 0 0
  1. from sqlalchemy.orm import declarative_mixin
  2.  
  3. from database.main_DB import Session as session
  4.  
  5.  
  6. @declarative_mixin
  7. class BaseMixin:
  8.     @classmethod
  9.     def create_or_update(cls, **kwargs):
  10.         """
  11.        :param kwargs: get dict example:
  12.                {'filter': {some dict},
  13.                'data': {some dict for create/update}
  14.                }
  15.        :return: instance
  16.        """
  17.         filter_data = kwargs.get('filter')
  18.         data = kwargs.get('data')
  19.         instance = session.query(cls).filter_by(**filter_data).first()
  20.  
  21.         if instance:
  22.             for key, value in data.items():
  23.                 if hasattr(instance, key):
  24.                     setattr(instance, key, value)
  25.         else:
  26.             instance = cls(**data)
  27.         return instance
  28.  
  29.     @classmethod
  30.     def get_or_create(cls, **kwargs):
  31.         """
  32.        :param kwargs: get dict example:
  33.                {'filter': {some dict},
  34.                'data': {some dict for create/update}
  35.                }
  36.        :return: instance
  37.        """
  38.         filter_data = kwargs.get('filter')
  39.         data = kwargs.get('data')
  40.         instance = session.query(cls).filter_by(**filter_data).first()
  41.         if instance:
  42.             return instance
  43.         else:
  44.             instance = cls(**data)
  45.         return instance
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement