On Fri, Aug 20, 2010 at 10:34 AM, Daniel Kluev <[email protected]> wrote:
>
> On Fri, Aug 20, 2010 at 7:39 AM, Eduardo Robles Elvira <[email protected]>
> wrote:
>>
>> Now, these functions reimplemented in the inherited class models might
>> be called by the jobs view. It would be very convenient if directly
>> when I get the jobs from the database with sqlalchemy I could directly
>> get them in "CustomJobA", "CustomJobB" instances, instead of all being
>> instances from the base clas "Job". There's a field in the base Job
>> class which tells me which class type it is (basically, it's
>> path.to.module and then ClassName).
>>
>
> SQLAlchemy supports this out of the box.
> http://www.sqlalchemy.org/docs/reference/ext/declarative.html#single-table-inheritance
>
> So it will be something like this:
>
> class Job(Base):
> class_name = Column(Unicode(64))
> __mapper_args__ = {'polymorphic_on': class_name}
>
> class CustomJobA(Job):
> __mapper_args__ = {'polymorphic_identity': 'CustomJobA'}
>
> SQLAlchemy will then load correct class instance for you on queries,
> depending on the value of the field.
>
> --
> With best regards,
> Daniel Kluev
Thanks Diez and Daniel for the responses. It seems that this is the
way to go, but it's not quite there yet: now I can indeed load the
correct lass instance for my queries, but it seems to be restricted to
inherited classes already loaded in my current module. What would like
to do is being to do something more similar to (conceptually!):
class Job(Base):
class_path = Column(Unicode(64)) # for example "CustomJobA"
module_path = Column(Unicode(64)) # maybe "plugins.myplugin.path.to.module"
def get_class_name(self):
modz = __import__(self.module_path, fromlist=["True"])
clazz = getattr(modz, self.class_path)
globals()[clazz.__name__] = clazz
class_name = property(get_class_name)
__mapper_args__ = {'polymorphic_on': class_name}
then, in plugins/myplugin/path/to/module.py:
class CustomJobA(Job):
__mapper_args__ = {'polymorphic_identity': 'CustomJobA'}
Where I don't necessary have the class CustomJobA from module
plugins.myplugin.path.to.module imported in the first place, but it
will be loaded. Of course, what I just wrote up there seems reaally
hacky and probably there's a better way? To be honest, I haven't even
tested if it even works yet.
Regards,
Eduardo RE.
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.