In SqlAlchemy how to share function between different table ORM

Viewed 18

I wrote some table ORM in SqlAlchemy, and I want to share common functionality between them, this is my table ORM:

class RetailCampaignTemp(Base, Serialize, PrimaryField):
    __tablename__ = 'retail_campaign_temp'
    clicks = Column(INTEGER(11))
    id = Column(INTEGER(11), primary_key=True)

Here are my custom functions:

class Serialize(object):
    def Serialize(self):
        return {c: getattr(self, c) for c in inspect(self).attrs.keys()}

class PrimaryField(object):

    @declared_attr
    def GetPrimaryField(cls):
        yield from (column for column in cls.columns if column.primary_key)  

When I call RetailCampaignTemp.GetPrimaryField() it say 'generator' object is not callable, what does this mean?

1 Answers

The culprit here is the @declared_attr decorator, which creates a class property, not a class method - that is, the expression RetailCampaignTemp.GetPrimaryField is already running the function body and returning the resulting generator, and RetailCampaignTemp.GetPrimaryField() is trying to call this generator.

This decorator is designed to be used to dynamically create sqlalchemy mapping/table declarations, e.g. by returning a relationship. From your example code it doesn't look like this is the case, so is there any reason you're not just using python's builtin @classmethod instead? This would make your call RetailCampaignTemp.GetPrimaryField() valid.

Related