On Mar 5, 2012, at 9:33 PM, Pete Erickson wrote:
> book, and there is no BookProduct. That being the case, I'd still like
> the generic Product to persist, but it just won't have additional
> attributes specific to a book. Once the BookProduct is created, I can
> go back and fix it... so the question is, can I do the following and
> when I query the db I get HardwareProducts, SoftwareProducts, and
> Products?
> 
> class Product(Base):
>    __tablename__ = 'products'
> 
>    id = Column(Integer, Sequence('product_id_seq'), primary_key=True)
> 
>    # read from the xml file
>    type = Column(String(16))
> 
>    # used for SA's polymorphic ability
>    poly_type = Column(String(16))
> 
>    __mapper_args__ = {'polymorphic_on': poly_type}
> 
> class HardwareProduct(Base):
>    __tablename__ = 'hardware'
>    __mapper_args__ = {'polymorphic_identity': 'hardware'}
>    id = Column(Integer, ForeignKey('products.id'), primary_key=True)
>    ...
> 
> pi = ProductInfo('xml_file')
> 
> if pi.type == 'hardware':
>    p = HardwareProduct(pi.__dict__)
> elif pi.type == 'software':
>    p = SoftwareProduct(pi.__dict__)
> else:
>    p = Product(pi.__dict__)
> 
> session.add(p)
> 

One thing to keep in mind is if "bookproduct" is added, then you load more XML 
files in treating "bookproduct" as plain Product, then later you want to "fix 
it", it means you have to migrate data into a new "book" table.

Anyway the approach you have above is fine, with Product as a fallback, just 
give it a polymorphic identity  (like 'product') in the __mapper_args__ dict.  




-- 
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.

Reply via email to