you would need to query the database for an already existing Keyword object first. I.e.:
existing_keyword = Session.query(Keyword).filter(Keyword.name=='test image').first() if existing_keyword is None: existing_keyword = Keyword(name='test image') There's a recipe that can help with the "create object if doesn't exist" paradigm. That is at http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject . On Nov 18, 2010, at 12:56 PM, Sujeevan Rasaratnam wrote: > Hello, > I am new to SQLAlchemy and I couldn't find a way to properly associate many > to many relation. My environment: python 2.6, SQLAlchemy 0.6.5, Postgres > 8.4.5. How do I associate to a already existing row in many to many relation. > > ################ > class Keyword(Base): > __tablename__ = 'keywords' > > id = Column(Integer, primary_key=True, autoincrement=True) > name = Column(Unicode, unique=True, nullable=False) > description = Column(Unicode, nullable=True) > > class ImageKeyword(Base): > __tablename__ = 'image_keywords > image_id = Column(Integer, ForeignKey('images.id', onupdate = 'CASCADE', > ondelete = 'CASCADE'), primary_key=True) > keyword_id = Column(Integer, ForeignKey('keywords.id', onupdate = > 'CASCADE', > ondelete = 'CASCADE'), primary_key=True) > > class Image(Base): > __tablename__ = "images" > id = Column(Integer, primary_key=True) > name = Column(Unicode, unique=True, nullable=False) > > keywords = relationship(Image, > secondary="image_keyword", > backref='images') > def addKeywords(self, keywords): > for keyword in keywords: > self.keywords.append(Keyword(name=keyword)) > > # Add > session = Session() > i = Image() > i.name = "image1" > i.addKeyword(['test image', 'first image']) > session.add(i) > session.commit() > > i = Image() > i.name = "image2" > i.addKeyword(['test image']) > session.add(i) > session.commit() > #This will fail because of the unique constraint of Keyword.name > # What is the proper way? > > ######################### > > Thank you > > > Sujeevan Rasaratnam > > -- > 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. -- 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.