In `Company.__init__()`, instead of blindly creating a new `Creator` instance, 
you need to first query for an existing Creator with that name. If it exists, 
append it, otherwise, create a new one and append that. 

-- 
Tim Van Steenburgh


On Monday, August 12, 2013 at 9:26 PM, [email protected] wrote:

> I have another question about a piece of code that I posted the other day. 
> Namely, I have a one-to-many relationship between Creator and Company. A 
> Creator can have a relationship with multiple Companies but any one Company 
> can have a relationship with only one Creator.
> 
> class Company(Base):
>     __tablename__ = "companies"
>     id = Column(Integer, primary_key = True)
>     company = Column(String(100), unique=True, nullable=False)
>     creator = relationship("Creator", backref="companies", cascade="all")
> 
> 
>     def __init__(self, company, creator):
>         self.company = company
>         self.creator.append(Creator(creator))
> 
> class Creator(Base):
>     __tablename__ = "creators"
> 
>     company_id = Column(Integer, ForeignKey('companies.id 
> (http://companies.id/)'))
>     creator = Column(String(100), nullable=False, unique=True)
> 
>     def __init__(self, creator):
>         self.creator = creator
> 
> 
> So, to create a Company, the code calls company = Company(<company name>, 
> <creator name>) and that in turn calls Creator().
> 
> The problem is that the Companies get added one by one, and if a new company 
> being entered has a Creator with a name of a preexisting company, SQLalchemy 
> errors due to the unique=True flag:
> 
> sqlalchemy.exc.IntegrityError: (IntegrityError) (1062, "Duplicate entry 
> 'Viking' for key 'creator'") 'INSERT INTO creators (company_id, creator) 
> VALUES (%s, %s)' (17L, u'Viking')
> 
> If unique=True isn't enabled, it will create another Creator of the same 
> name. Instead, the code should reflect the additional Company assigned to 
> this particular Creator. How might I go about fixing this?
> 
> Thanks! 
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "sqlalchemy" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to [email protected] 
> (mailto:[email protected]).
> To post to this group, send email to [email protected] 
> (mailto:[email protected]).
> Visit this group at http://groups.google.com/group/sqlalchemy.
> For more options, visit https://groups.google.com/groups/opt_out.
>  
>  

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to