0

I use: Python 2.6 and sqlalchemy 0.6.1

This is what I am trying to do:

from sqlalchemy.types import (
    Integer,
    String,
    Boolean
)
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class SampleMeta(type):
    def __new__(cls, name, bases, attrs):
        attrs.update({   'id': Column('Id', Integer, primary_key=True),
                    'name': Column('Name', String),
                    'description': Column('Description', String),
                    'is_active': Column('IsActive', Boolean)
                })
        return super(SampleMeta, cls).__new__(cls, name, bases, attrs)

class Sample(Base):
    __tablename__ = 'Sample'
    __table_args__ = {'useexisting': True}
    __metaclass__ = SampleMeta

    def __init__(self, id, name, description, is_active):
        self.id = id
        self.name = name
        self.description = description
        self.is_active = is_active

    def __repr__(self):
        return "<(%d, '%s', '%s', %r)>" % (self.id, self.name, self.description, self.isactive)

And the error I am getting is this:

TypeError: Error when calling the metaclass bases
    metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

Now, if I do the same thing above by using

class Sample(object)

instead of

class Sample(Base)

it works absolutely fine.

I need to update the attributes of the class dynamically. So, I will be using dynamic attribute and column names. And I need the above piece code to work in order to be able to get there.

Please help

2
Contributors
1
Reply
35
Views
4 Years
Discussion Span
Last Post by Gribouillis
0

I suggest something along the lines of

from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base

class SampleMeta(DeclarativeMeta):
    def __init__(cls, name, bases, attrs): # this is __init__ !
        attrs.update({   'id': Column('Id', Integer, primary_key=True),
                    'name': Column('Name', String),
                    'description': Column('Description', String),
                    'is_active': Column('IsActive', Boolean)
                })
        DeclarativeMeta.__init__(cls, name, bases, attrs)

Base = declarative_base(metaclass = SampleMeta)

class Sample(Base):
    # etc

Edited by Gribouillis

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.