1

I have 2 tables with the same column structure.

The script pulls from 2 different json sources with slightly different keys.

My Item class identifies the source and then parses the data.

In my Item class I want to be able to change the __tablename__ based on the data source.

Is this possible or do I need to write a separate class for each data source?

Thanks,

Code:

Base = declarative_base()


class Item(Base):
    __tablename__ = 'products'

    timestamp = Column(TIMESTAMP)
    itemid = Column(String, primary_key=True, index=True, unique=True)
    name = Column(String)    

    def __init__(self, item):

        if type(item) == Product_A:
            self.__tablename__ = "A_products"
            # Parse Data
        elif type(item) == Product_B:
            self.__tablename__ = "B_products"
            # Parse Data

1 Answer 1

2

This is not a good idea, in sqlalchemy each class should be mapped to a single table. A solution is to make two classes and a free function to dispatch between them:

Base = declarative_base()
class Item_A(Base):
    __tablename__ = 'A_products'
    timestamp = Column(TIMESTAMP)
    itemid = Column(String, primary_key=True, index=True, unique=True)
    name = Column(String)    

class Item_B(Base):
    __tablename__ = 'B_products'
    timestamp = Column(TIMESTAMP)
    itemid = Column(String, primary_key=True, index=True, unique=True)
    name = Column(String)    

def create_item_object(item):
    if isinstance(item, Product_A):
        result = Item_A()
        #... more stuff
    elif isinstance(item, Product_B):
        result = Item_B()
        #... more stuff
    return result
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.