On Jun 18, 2011, at 2:24 AM, Fayaz Yusuf Khan wrote:

> Hi, I'm a SQLA and MySQL noob.
> I have a many to one relationship somewhat similar to this:
> 
> class Parent(Base):
>    ...
>    name = Column(String, primary_key=True)
> 
> class Child(Base):
>    ...
>    parent = Column(String, ForeignKey('Parent.name'))
> 
> And I'm trying to do this:
> 
> session.add(Child(..., name='NewParent',...))
> 
> But on commit, it raises an IntegrityError.
> 
> How can I make SQLA automatically insert a Parent in this case?


SQLA doesn't automatically "create" any objects so you'd need to create the 
Parent object yourself, but you'd also use relationship():

class Child(Base):
    parent_name = Column(String, ForeignKey('parent.name'))
    parent = relationship(Parent)

    def __init__(self, name):
        self.parent = Parent(name)


relationship() would handle the "parent_name" assignment as well as adding 
Parent to the Session.


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