On Apr 7, 9:29 pm, "Michael Bayer" <mike...@zzzcomputing.com> wrote: > Tvrtko wrote: > > I have a schema that cannot be changed. In it, there is a table with > > two columns: > > > element_type CHAR(1) > > element_id INTEGER > > > There is no foreign key on element_id because it can point to > > different, unrelated > > tables (element_type) says where element_id points to. > > > How can I model this in sqlalchemy? > > this is a rails-style "polymorphic association" (note that Hibernate calls > it this as well: "The <any> mapping element defines a polymorphic > association to classes from multiple tables."). See the example > examples/poly_assoc/poly_assoc.py in the distro as well as the discussion > athttp://techspot.zzzeek.org/?p=13.
Thanks. It s good to know that I can just pretend that there are foreign keys between the tables. This actually helps in more cases than just this one! > > > I know how to load and store element using property: > > > def _get_element(self): > > if self.need_element_reload(): > > clazz = self.get_class_from_type(self._element_type) > > self._element = > > object_session(self).query(clazz).get(self.element_id) > > return self._element > > def _set_element(self, element): > > self._element_type = self.get_type_from_instance(element) > > self._element_id = element.id if element else None > > self._element = element > > element = property(_get_element, _set_element) > > > But this is not good enough. For example, if I create new element > > which > > is not yet flushed, there is no id. Normally, sqlalchemy knows about > > relationships and finishes the foreign key column assignment > > once the pointed-to id is known. How can I model this type of > > relationship so that sqlalchemy will do the right thing > > (assign element_id in a flush process, or more generally behave > > like this is a normal relationship). > > > I'm not sure if I explained it correctly, so I'll just mention that > > hibernate has <any> element that can do just that. > > > Thanks, > > Tvrtko -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.