在Flask中实现Reddit类型投票,可以通过使用包含User、Post和Vote模型的辅助表来实现。下面是对这个问题的完善且全面的答案:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship('User', backref=db.backref('posts', lazy=True))
class Vote(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
vote_type = db.Column(db.Enum('upvote', 'downvote'), nullable=False)
user = db.relationship('User', backref=db.backref('votes', lazy=True))
post = db.relationship('Post', backref=db.backref('votes', lazy=True))
请注意,以上推荐的腾讯云产品仅供参考,具体选择应根据实际需求进行评估和决策。
领取专属 10元无门槛券
手把手带您无忧上云