2010-02-22 50 views
16

假設我在SQLALchemy中有3個類:Topic,Tag,Tag_To_Topic在SQLAlchemy中以多對多關係插入數據

是否可以寫類似:

new_topic = Topic("new topic") 
Topics.tags = ['tag1', 'tag2', 'tag3'] 

,我想自動插入變量表「標籤1」,「標籤2」和「標籤3」,並插入new_topic之間的正確關係這3個標籤在Tag_To_Topic表中。

到目前爲止,我還沒有弄清楚如何做到這一點,因爲多對多的關係。 (如果它是一對多的,這將是非常容易的,SQLAlchemy會默認它,但這是多對多的。)

這可能嗎?

謝謝,Boda Cydo。

回答

15

您可以通過使用association_proxy來簡化您的多對多關係。

然後,我會離開的關係,因爲它是爲了不與什麼SA確實會干擾:

# here *tag_to_topic* is the relation Table object 
Topic.tags = relation('Tag', secondary=tag_to_topic) 

我建議你剛剛創建,做翻譯的字符串工作的簡單包裝屬性列表到關係對象(你可能會重命名關係)。您的標籤類將類似於:

class Topic(Base): 
    __tablename__ = 'topic' 
    id = Column(Integer, primary_key=True) 
    # ... other properties 

    def _find_or_create_tag(self, tag): 
     q = Tag.query.filter_by(name=tag) 
     t = q.first() 
     if not(t): 
      t = Tag(tag) 
     return t 

    def _get_tags(self): 
     return [x.name for x in self.tags] 

    def _set_tags(self, value): 
     # clear the list first 
     while self.tags: 
      del self.tags[0] 
     # add new tags 
     for tag in value: 
      self.tags.append(self._find_or_create_tag(tag)) 

    str_tags = property(_get_tags, 
         _set_tags, 
         "Property str_tags is a simple wrapper for tags relation") 

那麼這個代碼應工作:

# Test 
o = Topic() 
session.add(o) 
session.commit() 
o.str_tags = ['tag1'] 
o.str_tags = ['tag1', 'tag4'] 
session.commit() 
+0

我現在想這個。非常感謝您的幫助! – bodacydo 2010-02-22 12:05:15

+0

我想向你表示深深的謝意,Van,幫助我。您使用關聯代理的建議,以及通過添加輔助方法來改進類的結果都是很好的代碼和解決方案。謝謝! – bodacydo 2010-02-23 09:59:08

+0

謝謝,麪包車。但是,如何「選擇」標籤,例如,讓標籤爲「news」和o.year> 2010的所有主題(只是Topic()實例中的一個任意屬性)? – 2014-08-25 08:24:57