2017-10-08 152 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

相关问题