我对关系数据库和Web编程一般都很陌生,我面临着如何构建数据库以使用投票系统的问题,类似于reddit。
我正在使用sqlalchemy,重要的位如下所示:
class Vote(Base):
__tablename__ = 'votes'
id = Column(Integer, primary_key = True)
vote_type = Column(Integer, default = 0)
user_id = Column(Integer, ForeignKey('users.id'))
#article_id = Column(Integer, ForeignKey('article_items.id'))
#comment_id = Column(Integer, ForeignKey('comments.id'))
class ArticleItem(Base):
__tablename__ = 'article_items'
id = Column(Integer, primary_key = True)
vote_ups = Column(Integer, default = 0)
vote_downs = Column(Integer, default = 0)
article = relationship("Article",
uselist = False,
backref = 'article_item')
comments = relationship("Comment")
votes = relationship("Vote", cascade = "all")
class Comment(Base):
__tablename__ = 'comments'
id = Column(Integer, primary_key = True)
data = Column(Text, nullable = False)
replies = relationship("Comment")
vote_ups = Column(Integer, default = 0)
vote_downs = Column(Integer, default = 0)
votes = relationship("Vote", cascade = "all")
parent_id = Column(Integer, ForeignKey('comments.id'))
article_id = Column(Integer, ForeignKey('article_items.id'))
现在,我必须在class Vote
中包含两个外键,但在任何时候都只使用两个键中的一个。
有没有更容易/推荐的方法来做到这一点?我应该保留两种不同的投票类型;一个用于评论,一个用于文章?或者我应该将ArticleItem
和Comment
合并为一个class Voteable
?