2017-10-08 204 views
0

前提條件:從預定列表中搜索項目實例的公共註釋(字符串)。在單個評論中可以有多個列表匹配。添加到SQLAlchemy的多對多關係

我正在嘗試使用多對多結構來跟蹤這一點。

我創建使用SQLAlchemy的(Python的3.5)

reddit_assoc = Table('reddit_assoc', Base.metadata, 
    Column('comment_id', Integer, ForeignKey('reddit_comments.comment_id')), 
    Column('character_id', Integer, ForeignKey('characters.character_id')) 
    ) 

class characters(Base): 
    __tablename__ ='characters' 

    character_id = Column(VARCHAR(20),primary_key=True) 
    name = Column(VARCHAR(3072)) 
    added = Column('added', DateTime, default=datetime.datetime.now()) 
    reddit_mentions = relationship('reddit_comments', secondary='reddit_assoc', back_populates='character_mentions') 

class reddit_comments(Base): 
    __tablename__ = 'reddit_comments' 
    comment_id = Column(VARCHAR(50), primary_key=True) 
    comment_author = Column(VARCHAR(300)) 
    comment_created = Column(VARCHAR(300)) 
    link_id = Column(VARCHAR(50)) 
    subreddit_id = Column(VARCHAR(50)) 
    character_mentions = relationship('characters', secondary='reddit_assoc', back_populates='reddit_comments') 

並使用下面找到匹配

def char_counter(comment): 
    Session = DBSession() 
    reader = Session.query(characters).all() 

    for char in reader: 
     if char[0] in comment['comment_body'] or char[1] in comment['comment_body']: 
      # We have a match. Add to database. 
      Session.merge(reddit_comments(#relevant information from comment#)) 
      #How do I add to the Many to Many here? 
      Session.commit() 
     Session.close() 

問題以下數據庫結構:尋找在評論以上片段,我不明白我如何添加可能多個字符匹配的關係從通信ent ['comment_body']字符串正確地轉換爲reddit_assoc關聯表。有人可以請進一步建議嗎?

回答

1

您在本例中使用的關係表現爲列表。所以你需要添加新創建的reddit評論列表reddit_mentions

def char_counter(comment): 
    Session = DBSession() 
    reader = Session.query(characters).all() 

    for char in reader: 
     if char[0] in comment['comment_body'] or char[1] in comment['comment_body']: 
      # We have a match. Add to database. 
      rc = reddit_comments(#relevant information from comment#) 
      Session.flush() # to ensure you have primary key, although may not be needed 
      char.reddit_mentions.append(rc) # this will eventually fill your reddit_assoc table 
      Session.add(char) 

    # move this outside of loop   
    Session.commit() 
    Session.close() 
+0

請注意,'Session.merge()的返回'合併實例作爲一個新的實例,所以'rc'不實際添加到會話,直到'reader.reddit_mentions.append(RC)'被調用,如果「來自評論的相關信息」不包含主鍵,則將插入2行而不是1行。這不會發生,因爲代碼會在'Session.flush(rc)'引發'TypeError',因爲'flush()'需要一個迭代的實例對象。最後,這裏的'reader'是一個'characters'實例的列表,所以'Session.add(reader)'也會引發。 –

+0

當然'reader.reddit_mentions.append(rc)'也會增加,因爲'list'沒有屬性reddit_mentions。 –

+0

@IljaEveriläyap,我的錯誤,改變了代碼 – PerunSS

相關問題